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.
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.