Last updated on July 14, 2020 by Dan Nanni
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
bashshell scripting tutorials provided by Xmodulo.
Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.