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)"
Following are commonly used options.
Option | Description | Example |
---|---|---|
%Y | Year | 2018 |
%y | Year | 18 |
%m | Month | 01 |
%b | Month | Jan |
%B | Month | January |
%d | Day | 14 |
%H | Hour (24 hour format) | 22 |
%I | Hour (12 hour format) | 10 |
%M | Minute | 56 |
%S | Second | 23 |
%p | AM or PM | AM |
%P | am or pm | pm |
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')