2

我可以.bash_profile在用户登录系统时运行命令。我想禁止在特定时间登录。算法:

if((HOUR(now) == 13) || (HOUR(now) < 7))
    exit

我知道,如何在 C 中做这样的事情:

#include <stdio.h>
#include <time.h>

int main(int argc, char *argv[])
{
    time_t rawtime; time (&rawtime);
    struct tm *tm_struct = localtime(&rawtime);

    int hour = tm_struct->tm_hour;

    if((hour == 13) || (hour < 7))
    {
        printf("hi\n");//exit will be used instead
    }

    return 0;
}

但我不知道如何在 bash 中实现它。

4

3 回答 3

6

必须小心date +%H-- 当它返回“08”或“09”时,然后你尝试在算术表达式中使用它,你会得到无效的八进制错误:

$ hour="09"
$ if (( hour == 13 || hour < 7 )); then echo y; else echo n; fi
bash: ((: 09: value too great for base (error token is "09")
n

您可以明确告诉 bash 您的数字是以 10 为底的:

$ if (( 10#$hour == 13 || 10#$hour < 7 )); then echo y; else echo n; fi
n

或者,使用不同的日期格式说明符:我的日期手册页说%k%_H返回空格填充小时(0..23)

hour=$(date +%_H)
if (( hour == 13 || hour < 7 )); then ...
于 2013-09-18T19:41:05.027 回答
3
#!/bin/bash
HOUR=`date +%H`
if [ $HOUR -eq 13 -o $HOUR -lt 7 ];then
    exit
fi

请注意,与()[]解释09为八进制数不同

于 2013-09-18T18:43:22.933 回答
2

使用date命令只返回小时:

hour=$(date +%H)
if (( hour == 13 || hour < 7 )); then
    exit
fi
于 2013-09-18T18:42:27.010 回答