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:

[bash]
TODAY=$(date|awk ‘{ print $1 }’)
TODAY=`date ‘+%A’`
NUMBER-OF-DAY-IN-WEEK=`date +%u`
MONTH=$(date|awk ‘{ print $1 }’)
MONTHNAME=`date +%b –date ‘0 month’`
DAYINMONTH=$(date|awk ‘{ print $3 }’)
YEAR=$(date | awk ‘{ print $6 }’)
WEEKNUMBER=`date +"%V"`
[/bash]

 

[bash]
# 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;;
esac
dte1=$(date2stamp $1)
dte2=$(date2stamp $2)
diffSec=$((dte2-dte1))
if ((diffSec < 0)); then abs=-1; else abs=1; fi
echo $((diffSec/sec*abs))
}
[/bash]

Here is useful reading:
http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/

Leave a Reply

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