How to format the date in a bash script

Home > Search > How-to
  by

Let's say you have a file date.sh. The following is the absoulte minimal code needed to produce the date in a BASH script.

#!/bin/bash
date

 

Running this script will produce the following:

Wed Nov 30 19:01:23 CST 2016

 


Echo date inline

Let's say we want to add some text before the date.

#!/bin/bash
echo "The current date and time is $(date)"

 

Running this script will produce the following:

The current date and time is Wed Nov 30 19:01:23 CST 2016

 


Format the date

Typically, the entire date string, with the date of the week, month, date, time, time zone, and year, is not what we want. We can customize this output by selecting the particular elements we want to display.

#!/bin/bash
echo "The current date is $(date +%m-%d-%Y)"

 

Running this script will produce the following:

The current date and time is 11-30-2016

 

%F can be used for the year (and %T for the time) to reduce the amount of options needed to format the date.

#!/bin/bash
echo "The current date is $(date +%F)"

 


Variable

We can put the date in a variable and then use an if / else statement to display certain text based on the statement.

#!/bin/bash
today=$(date +%m-%d-%Y)

if [ $today == "2016-11-30" ]
then
  echo "True"
else
  echo "False"
fi

 

Running this script will produce the following:

False

 


Two weeks from today

Sometimes, you need to use some future date, such as 14 days from today. 

#!/bin/bash
two_weeks=$(date '+%m-%d-%Y' -d '+14 days')

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments