Using date and time in Bash scripts

Date and time is useful. You might want your script to check if it is Monday today, or if the script ran 2 days ago. Maybe you need to save a file with the current date and time. Here are some variables that I use to put in my bash scripts:

TODAY=$(date|awk ‘{ print $1 }’)
TODAY=`date ‘+%A’`
MONTH=$(date|awk ‘{ print $1 }’)
MONTHNAME=`date +%b –date ‘0 month’`
DAYINMONTH=$(date|awk ‘{ print $3 }’)
YEAR=$(date | awk ‘{ print $6 }’)
WEEKNUMBER=`date +"%V"`


# Date to unixstamp
date2stamp () {
date –utc –date "$1" +%s
stamp2date (){
date –utc –date "1970-01-01 $1 sec" "+%Y-%m-%d %T"
dateDiff (){
case $1 in
-s) sec=1; shift;;
-m) sec=60; shift;;
-h) sec=3600; shift;;
-d) sec=86400; shift;;
*) sec=86400;;
dte1=$(date2stamp $1)
dte2=$(date2stamp $2)
if ((diffSec < 0)); then abs=-1; else abs=1; fi
echo $((diffSec/sec*abs))

Here is useful reading:

Leave a Reply

Your email address will not be published. Required fields are marked *