Articles: Get the Current Hour/Minute and Time Comparison Logic for BASH Script in Linux
Posted by: david on 03/29/2011 - 04:14 PM
On one of our Linux servers running CentOS 5 I wanted to run a cron job on a script that download a certain file every 15 minutes, but the source hosting the file only allows up to a certain downloads daily. Therefore I needed to get some sort of logic in the bash script so that it skips certain hours. To get the current hour and store it in a variable, I had in the file:cur_hour=$(date +"%H");
If you also need to get the current minute, you would do a:
cur_min=$(date +"%M");
in the script.
I use the "wget" command to grab the file, but I only want it to happen if it's 5 AM & later and before 11 PM, and this is how I did it:
if [ $cur_hour -ge 4 -a $cur_hour -lt 23 ]; then
/usr/local/bin/wget -t0 -O '/tmp/destination_file' "http://source_of_file"
fi
Hopefully this tip and example helps anyone looking for a way to bash programming with date and time.