QA Graphic

BASH Date

None

Recently I needed to use date formatting in some Bash scripts that I was writing. I was a little surprise on how hard it was to find how to add date and assign it to a variable.

Below are a couple of examples that I created to help others who are encountering the same issue. Here are a couple of Bash scripts and how to assign a date and manipulate the date too.

Note: There is a slight difference in date formatting between BSD and GNU. (OS X users take note on the BSD formatting.)

BSD:
#!/bin/bash
todaydate=$(date +"%B %d, %Y"")
yesterday=$(date -v -1d  +"%B %d, %Y")
lastmonth=$(date -v -1m  +"%B %d, %Y")
tomorrow=$(date -v +1d  +"%B %d, %Y")
lastyear=$(date -v -1y  +"%B %d, %Y")
ninetydaygoals=$(date -v +90d  +"%B %d, %Y")
echo "Yesterday was $yesterday"

GNU:
#!/bin/bash
todaydate=$(date +"%d/%b/%Y")
yesterday=$(date --date="-1 day" +"%B %d, %Y")
lastmonth=$(date --date="-1 month" +"%B %d, %Y"")
tomorrow=$(date --date="+1 day" +"%B %d, %Y"")
lastyear==$(date --date="-1 year" +"%B %d, %Y"")
ninetydaygoals=$(date --date="+90 day"  +"%B %d, %Y"")
echo "Yesterday was $yesterday"

 

Comments

Add Comments

Name:
Comment: