BASH如果条件

时间:2010-06-14 14:53:15

标签: bash scripting

我之前问了一个问题。答案是有道理的,但我永远无法让它发挥作用。现在我得让它运转起来。但我无法弄清楚BASH的if语句。我在下面做错了什么:

START_TIME=9
STOP_TIME=17
HOUR=$((`date +"%k"`))
if [[ "$HOUR" -ge "9" ]] && [[ "$HOUR" -le "17" ]] && [[ "$2" != "-force" ]] ; then
    echo "Cannot run this script without -force at this time"
    exit 1
fi

我的想法是,我不希望这个脚本在上午9点到下午5点之间继续执行,除非被强制执行。但它总是会将条件评估为true,因此不允许我运行脚本。

./ script.sh [action]( - force)

THX

编辑: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

然后使用-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

2 个答案:

答案 0 :(得分:0)

#!/bin/bash
START_TIME=9
STOP_TIME=17
HOUR=$(date +"%k")
if (( $HOUR >= $START_TIME && $HOUR <= $STOP_TIME )) && [[ "$2" != "-force" ]] ; then
    echo "Cannot run this script without -force at this time"
    exit 1
fi

答案 1 :(得分:0)

使用 -a 代替&amp;&amp;

if [ $HOUR -ge $START_TIME -a $HOUR -le $STOP_TIME -a "_$2" != "_-force" ]; then
    echo "Cannot run without -force at this hour"
    exit 1
fi