bash如何使用当前时间的小时数

use*_*035 2 bash time

我可以.bash_profile在用户登录系统时输入命令.我想在某些时间禁止登录.算法:

if((HOUR(now) == 13) || (HOUR(now) < 7))
    exit
Run Code Online (Sandbox Code Playgroud)

我知道,如何在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;
}
Run Code Online (Sandbox Code Playgroud)

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

gle*_*man 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
Run Code Online (Sandbox Code Playgroud)

你可以明确地告诉bash你的数字是10:

$ if (( 10#$hour == 13 || 10#$hour < 7 )); then echo y; else echo n; fi
n
Run Code Online (Sandbox Code Playgroud)

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

hour=$(date +%_H)
if (( hour == 13 || hour < 7 )); then ...
Run Code Online (Sandbox Code Playgroud)