How to append current date and timestamp to filename in shell script

Sometimes it is useful to include current date or timestamp information in file names, especially when files are generated on a regular basis such as monthly/daily/hourly for backup, logging and other archiving purposes. Here is how you can format current date and time, and append formatted string to a file name, in a shell script.

A linux command line tool called date allows you to format the display of current time as you want. So you can use this command in a shell script. The syntax of date command is shown as follows.

$ date +"FORMAT"

To include current time in second precision:

now=$(date +"%Y-%m-%d-%S")
filename="my_program.$now.log"
# example filename: my_program.2012-01-23-47.log

To include current timestamp in nanosecond precision:

now=$(date +"%Y.%m.%d.%S.%N")
filename="my_program.$now.log"
# example filename: my_program.2013.01.23.44.364617000.log

To include current timestamp in epoch (i.e., number of seconds elapsed since 1970-1-1):

now=$(date +"%s")
filename="my_program.$now.log"
# example filename: my_program.1358995092.log

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.
Your name can also be listed here. Write for us as a freelancer.

One thought on “How to append current date and timestamp to filename in shell script

  1. Hi,

    How can I implement a script to get the time stamp for the jobs we run?
    I have a script. I'll run 10 jobs in unix. And I want to know the time elapsed for 10 jobs. so that I can calculate time elapsed for each job. Which command do I have to use in a script to get time elapsed for jobs?

Leave a comment

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