I'm trying to figure this out on and off for some time now. I have a bash script in Linux environment that, for safety reasons, I want to prevent from being executed say between 9am and 5pm unless a flag is given. So if I do ./script.sh between 9am and 5pm it would say "NO GO", but if I do ./script.sh -force it would bypass the check. Basically making sure the person doesn't do something by accident. I've tried some date commands, but can't wrap that thing around my mind. Could anyone help out?
+2
A:
Write a function. Use date +"%k"
to get the current hour, and (( ))
to compare it.
Ignacio Vazquez-Abrams
2010-01-15 16:38:26
What is (( )) ???
Daniil
2010-01-15 16:47:40
It evaluates an arithmetic expression in bash. `help '(('`
Ignacio Vazquez-Abrams
2010-01-15 16:48:55
OK, I have this. Would that work:HOUR=$((`date +"%k"`))if (( HOUR >= 9 then echo "NO GO" exitfiecho "GOING..."
Daniil
2010-01-15 17:07:50
`HOUR=$(date +"%k")` and don't forget the `else` on the if.
Ignacio Vazquez-Abrams
2010-01-15 17:09:32
Actually, With the exit you don't need the else, so skip that. I blame that on this tiny comment space. I do recommend e.g. `exit 1` though.
Ignacio Vazquez-Abrams
2010-01-15 17:12:49
There'd need to be newlines or semi-colons in the script; I can see one semi-colon, but newlines were probably flattened by the lack of formatting in the comment mechanism.
Jonathan Leffler
2010-01-15 17:24:45
Somehow newlines didnt make it in the comments. Thank you!
Daniil
2010-01-15 17:29:41
+2
A:
Basic answer:
case "$1" in
(-force)
: OK;;
(*)
case $(date +'%H') in
(09|1[0-6])
echo "Cannot run between 09:00 and 17:00" 1>&2
exit 1;;
esac;;
esac
Note that I tested this (a script called 'so.sh') by running:
TZ=US/Pacific sh so.sh
TZ=US/Central sh so.sh
It worked in Pacific time (08:50) and not in Central time (10:50). The point about this is emphasizing that your controls are only as good as your environment variables. And users can futz with environment variables.
Jonathan Leffler
2010-01-15 16:53:56
You can improve your chances if your date command has `--utc` which should make it ignore the time zone.
Dennis Williamson
2010-01-15 17:05:05
Yes, but then you need to know which time range to allow in UTC. Does the colleague in US/Eastern need the same time range ban as the colleague in US/Pacific time? Is it from 09:00 US/Eastern to 17:00 US/Pacific? Are the times in PST or PDT (Standard/Daylight Saving Time?)
Jonathan Leffler
2010-01-15 17:21:57
A:
Test script:
#!/bin/bash
HOUR=$(date +%k)
echo "Now hour is $HOUR"
if [[ $HOUR -gt 9 ]] ; then
echo 'after 9'
fi
if [[ $HOUR -lt 23 ]]; then
echo 'before 11 pm'
fi
Eduardo
2010-01-15 17:05:44