Elliot Reed Elliot Reed - 1 month ago 6
MySQL Question

BASH - If $TIME between 8am and 1pm do.., esle do.. Specifying time variables and if statements in BASH

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..

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..

Answer

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:

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.