BASH if 条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3038225/
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 conditions
提问by Daniil
I did ask a question before. The answer made sense, but I could never get it to work. And now I gotta get it working. But I cannot figure out BASH's if statements. What am I doing wrong below:
我之前确实问过一个问题。答案是有道理的,但我永远无法让它发挥作用。现在我必须让它工作。但我无法弄清楚 BASH 的 if 语句。我在下面做错了什么:
START_TIME=9
STOP_TIME=17
HOUR=$((`date +"%k"`))
if [[ "$HOUR" -ge "9" ]] && [[ "$HOUR" -le "17" ]] && [[ "" != "-force" ]] ; then
echo "Cannot run this script without -force at this time"
exit 1
fi
The idea is that I don't want this script to continue executing, unless forced to, during hours of 9am to 5pm. But it will always evaluate the condition to true and thus won't allow me to run the script.
这个想法是我不希望这个脚本在上午 9 点到下午 5 点之间继续执行,除非被迫。但它总是将条件评估为真,因此不允许我运行脚本。
./script.sh [action] (-force)
./script.sh [动作] (-force)
Thx
谢谢
Edit: The output of set -x:
编辑: set -x 的输出:
$ ./test2.sh restart
+ START_TIME=9
+ STOP_TIME=17
++ date +%k
+ HOUR=11
+ [[ 11 -ge 9 ]]
+ [[ 11 -le 17 ]]
+ [[ '' != \-\f\o\r\c\e ]]
+ echo 'Cannot run this script without -force at this time'
Cannot run this script without -force at this time
+ exit 1
and then with -force
然后用 -force
$ ./test2.sh restart -force
+ START_TIME=9
+ STOP_TIME=17
++ date +%k
+ HOUR=11
+ [[ 11 -ge 9 ]]
+ [[ 11 -le 17 ]]
+ [[ '' != \-\f\o\r\c\e ]]
+ echo 'Cannot run this script without -force at this time'
Cannot run this script without -force at this time
+ exit 1
采纳答案by Paused until further notice.
#!/bin/bash
START_TIME=9
STOP_TIME=17
HOUR=$(date +"%k")
if (( $HOUR >= $START_TIME && $HOUR <= $STOP_TIME )) && [[ "" != "-force" ]] ; then
echo "Cannot run this script without -force at this time"
exit 1
fi
回答by Hai Vu
Use -ainstead of &&:
使用-a而不是&&:
if [ $HOUR -ge $START_TIME -a $HOUR -le $STOP_TIME -a "_" != "_-force" ]; then
echo "Cannot run without -force at this hour"
exit 1
fi

