Playing With Time in Bash Shell
The “date” command in Bash shell offers a remarkable array of features that can be very useful in performing many system administration tasks. As you will see below, it is easy to determine date, time, day of week for any interval of time. This can be very useful for system automation tasks with “cron” and “at”.
Current date in a common database-style format (YYYY-MM-DD HH:MM:SS):
|
1 2 3 4 5 6 |
date +'%Y-%m-%d %H:%M:%S' Example: $ date +'%Y-%m-%d %H:%M:%S' 2012-02-24 19:19:22 |
—————————————————————–
Dates of yesterday and tomorrow:
|
1 2 3 4 5 6 7 8 9 10 |
date --date="yesterday" +'%Y-%m-%d' date --date="tomorrow" +'%Y-%m-%d' Examples: $ date --date="yesterday" +'%Y-%m-%d' 2012-02-23 $ date --date="tomorrow" +'%Y-%m-%d' 2012-02-25 |
—————————————————————–
Date of next Saturday and last Monday:
|
1 2 3 4 5 6 7 8 9 10 |
date --date="next saturday" +'%Y-%m-%d' date --date="last monday" +'%Y-%m-%d' Examples: $ date --date="next saturday" +'%Y-%m-%d' 2012-02-25 $ date --date="last monday" +'%Y-%m-%d' 2012-02-20 |
—————————————————————–
Date of four day ago and two weeks from now:
|
1 2 3 4 5 6 7 8 9 10 |
date --date="4 days ago" +'%Y-%m-%d' date --date="2 weeks" +'%Y-%m-%d' Examples: $ date --date="4 days ago" +'%Y-%m-%d' 2012-02-20 $ date --date="2 weeks" +'%Y-%m-%d' 2012-03-09 |
—————————————————————–
Convert current date/time to epoch time:
|
1 2 3 4 5 6 |
date -d "`date +'%Y-%m-%d %H:%M:%S'`" "+%s" Example: $ date -d "`date +'%Y-%m-%d %H:%M:%S'`" "+%s" 1330128938 |
—————————————————————–
Convert epoch time to date/time:
|
1 2 3 4 5 6 7 |
date -d @${epoch_time} "+%Y-%m-%d %H:%M:%S" Example: $ epoch_time=$(date -d "`date +'%Y-%m-%d %H:%M:%S'`" "+%s") ; echo ${epoch_time} ; date -d @${epoch_time} "+%Y-%m-%d %H:%M:%S" 1330129014 2012-02-24 19:16:54 |
—————————————————————–
Determine if one date is older or newer than the other
Let’s say you have a bill due on February 21, 2012. Today is February 24. You need to write a script that will tell you if a) the bill is past due; and b) if so, then by how many days
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/bin/bash today_epoch=$(date -d "`date +'%Y-%m-%d'`" "+%s") due_date="2012-02-21" due_date_epoch=$(date -d "${due_date}" "+%s") if [ ${today_epoch} -gt ${due_date_epoch} ] then past_due_days=$(echo "scale=0;(${today_epoch}-${due_date_epoch})/60/60/24"|bc -l) echo "The bill was due ${past_due_days} days ago." fi Example: $ if [ ${today_epoch} -gt ${due_date_epoch} ] > then > past_due_days=$(echo "scale=0;(${today_epoch}-${due_date_epoch})/60/60/24"|bc -l) > echo "The bill was due ${past_due_days} days ago." > fi The bill was due 3 days ago. |
-
Wooooody
-
Big Banger
-
Mr SoLo DoLo
-
PolishPokeyPimp
-
The Beatles
