tags:

views:

151

answers:

2
+2  Q: 

BASH if conditions

Hi, 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:

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

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.

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

Thx

Edit: The output of 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

$ ./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
A: 
#!/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
Dennis Williamson
Note that having `STOP_TIME` set to 17 will prevent the script from running all the way until 17:59. You may need to change that if you want to be able to run it during the interval 17:00-17:59 (inclusive) or test for hours and minutes for more precision.
Dennis Williamson
OK - it seems to be working. Yes, I don't want to have that script executed up until 6pm, hence the <= 17. Big thanks! But can you explain what I was doing wrong? Just feeling very stupid that cannot figure out what seems to be the simplest possible task.
Daniil
I can't see any reason why your version doesn't work. Add `set -x` right before that section and `set +x` right after and edit your question to show the resulting output.
Dennis Williamson
A: 

Use -a instead of &&:

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
Hai Vu
Chris Johnsen