Alexei Chirknuov
Alexei Chirknuov

Reputation: 51

How to run command inside bash script only during specified period of time?

Let say, I need "command" to be run only if current time is from 11:10am till 2:30pm. How this can be done in bash script?

Something like below written in pseudo-language:

#!/bin/bash
while(1) {
    if ((currentTime > 11:10am) && (currentTime <2:30pm)) {
        run command;
        sleep 10;
    }
}

Upvotes: 5

Views: 4156

Answers (3)

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

The other answers overlook that when a number starts with 0, Bash will interprete it in radix 8. So, e.g., when it's 9am, date '+%H%M' will return 0900 which is an invalid number in Bash. (not anymore).

A proper and safe solution, using modern Bash:

while :; do
    current=$(date '+%H%M') || exit 1 # or whatever error handle
    (( current=(10#$current) )) # force bash to consider current in radix 10
    (( current > 1110 && current < 1430 )) && run command # || error_handle
    sleep 10
done

Could be shortened a bit if you accept a potential 10s delay for the first run:

while sleep 10; do
    current=$(date '+%H%M') || exit 1 # or whatever error handle
    (( current=(10#$current) )) # force bash to consider current in radix 10
    (( current > 1110 && current < 1430 )) && run command # || error_handle
done

Done!


Look:

$ current=0900
$ if [[ $current -gt 1000 ]]; then echo "does it work?"; fi
bash: [[: 0900: value too great for base (error token is "0900")
$ # oooops
$ (( current=(10#$current) ))
$ echo "$current"
900
$ # good :)

As xsc points out in a comment, it works with the ancient [ builtin... but that's a thing of the past :).

Upvotes: 9

Idriss Neumann
Idriss Neumann

Reputation: 3838

You could try something like :

currentTime=$(date "+%H%M")
if [ "$currentTime" -gt "1110" -a "$currentTime" -lt "1430" ]; then
    # ...
fi
# ...

Or :

currentTime=$(date "+%H%M")
if [ "$currentTime" -gt "1110" ] && [ $currentTime -lt "1430" ]; then
    # ...
fi
# ...

Or :

currentTime=$(date "+%H%M")
[ "$currentTime" -gt "1110" ] && [ "$currentTime" -lt "1430" ] && {
    # ...
}
# ... 

See man date for more details. You can also use a cron job to do more than run this script from 11:30.

NB : for your loop, you could use something like :

while [ 1 ]; do 
    #...
done

Or :

while (( 1 )); do 
    #...
done

Upvotes: 2

xsc
xsc

Reputation: 6073

You can create a 4-digit number describing the current time with date +"%H%M". I think that could be used to compare against other times (in 24h-format) numerically:

while [ 1 ]; do
    currentTime=$(date +"%H%M");
    if [ "$currentTime" -gt 1110 ] && [ "$currentTime" -lt 1430 ]; then
        ...
    fi
    sleep 10;    # probably better to have this outside the if-statement
done

If you want to handle a timespan that includes midnight you just have to replace the && with ||.

Upvotes: 0

Related Questions