BASH - 如果 $TIME 在上午 8 点到下午 1 点之间执行..,esle 执行.. 在 BASH 中指定时间变量和 if 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18128573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BASH - If $TIME between 8am and 1pm do.., esle do.. Specifying time variables and if statements in BASH
提问by Elliot Reed
I need to run a command when something is entered in BASH with a certain time-frame, and if it's not that time run another command. Here's what I've got so far, but it doesn't appear to be working..
当在某个时间范围内在 BASH 中输入某些内容时,我需要运行一个命令,如果不是那个时间,则运行另一个命令。这是我到目前为止所得到的,但它似乎没有工作..
FLATTIME=$(date "+%H%M")
FLATTIME=${FLATTIME##0}
if ! [[ $FLATTIME -gt 1130 ]] ; then
mysql --host=192.168.0.100 --user=myself --password=mypass thedb << EOF
INSERT INTO $STAFFID values ('','$STAFFID','$THETIME','','$THEDATE','$DAYOFWEEK');
EOF
else
mysql --host=192.168.1.92 --user=myself --password=mypass thedb << EOF
UPDATE $STAFFID SET Out_Time='$THETIME' WHERE date='$THEDATE';
EOF
fi
Ideally what I'd like is to have something like: if the time is between 8am and 1pm do the first command, if the time is between 1pm and 11pm do the second command, else echo "someone's been at work too long". I've tried a few variations but no luck, it just seems to run the first command whatever I do..
理想情况下,我想要的是:如果时间在上午 8 点到下午 1 点之间执行第一个命令,如果时间在下午 1 点到晚上 11 点之间执行第二个命令,否则回显“某人工作太久了”。我已经尝试了一些变化,但没有运气,它似乎只是运行第一个命令无论我做什么..
回答by glenn Hymanman
In this case, you just need to look at the hour. Also, bash has syntax to specify the radix of a number, so you don't have to worry about 08 and 09 being invalid octal numbers:
在这种情况下,您只需要查看小时。此外,bash 具有指定数字基数的语法,因此您不必担心 08 和 09 是无效的八进制数:
H=$(date +%H)
if (( 8 <= 10#$H && 10#$H < 13 )); then
echo between 8AM and 1PM
elif (( 13 <= 10#$H && 10#$H < 23 )); then
echo between 1PM and 11PM
else
echo go to bed
fi
"10#$H" is the contents of the variable, in base 10.
“10#$H”是变量的内容,以 10 为基数。
Actually, better to use %k
instead of %H
to avoid the invalid octal problem.
实际上,最好使用%k
而不是%H
避免无效的八进制问题。
H=$(date -d '08:45' "+%H")
(( 13 <= H && H < 23 )) && echo ok || echo no
bash: ((: 08: value too great for base (error token is "08")
versus
相对
H=$(date -d '08:45' "+%k")
# ....................^^
(( 13 <= H && H < 23 )) && echo ok || echo no
no