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..
The if statement starts with the if keyword followed by the conditional expression and the then keyword. The statement ends with the fi keyword. If the TEST-COMMAND evaluates to True , the STATEMENTS gets executed. If TEST-COMMAND returns False , nothing happens; the STATEMENTS get ignored.
The keyword if is followed by a condition. This condition is evaluated to decide which statement will be executed by the processor. If the condition evaluates to TRUE, the processor will execute the statement(s) followed by the keyword then. In the syntax, it is mentioned as statement1.
means "if whatever is a directory and is not a symbolic link". ( -d will return true if the target is a symbolic link to a directory. The [ syntax is actually a synonym for the test command.
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.
Actually, better to use %k
instead of %H
to avoid the invalid octal problem.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With