HowTo: Get / Print Current Date in Unix / Linux Shell Script

Posted on in Categories , last updated October 31, 2012

How do I get the current date in Unix or Linux shell scripting and store it into a shell variable? How do I print the current date using Unix shell script?

You need to use the following syntax to print current date and time on screen:


date

To store current date and time to a variable, enter:
now=$(date)
OR
now=`date`

To print this date either use printf or echo statement:

echo "$now"
echo "Current date: $now"

OR use printf:

printf "%s\n" "$n"

You can format and display date using the following syntax:

date +'FORMAT'

### mm/dd/yyyy ###
date +'%m/%d/%Y'

## Time in 12 hr format ###
date +'%r'

Sample shell script

#!/bin/bash
now="$(date)"
printf "Current date and time %s\n" "$now"
 
now="$(date +'%d/%m/%Y')"
printf "Current date in dd/mm/yyyy format %s\n" "$now"
 
echo "Starting backup at $now, please wait..."
# command to backup scripts goes here
# ...

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

5 comment

Leave a Comment