Linux Shell Date Format for Log File Names

​ GNU coreutils basics

​ GNU coreutils (Photo credit: Nguyen Vu Hung (vuhung))

Linux shell users need a quick way to include the date and time in log file names. Ideally the format should not include any space or colon characters. A format that I like to use is YYYY-MM-DD_HHMMSS and if the log file is created less often, the right-most parts of the time format can be removed. This loosely follows some ISO standards for date and time formats in a way that will correctly sort in directory listings.

A great shell command for this is the standard “date” command. In Ubuntu/Debian and RHEL/CentOS this is provided by the “coreutils” package (GNU core utilities). Use something like the following to use this type of date+time format in your log file names (bash shell is assumed).

# get the date as a shell variable $myDate
myDate=`date +"%Y-%m-%d_%H%M%S"`

# substitute a real command for myCommand
# curly braces separate $myDate variable from end of file name
myCommand >${myDate}_log.txt

# or on the fly with no variable
myCommand >$(date +%Y-%m-%d_%H%M%S)_log.txt

# get documentation for the date command
date --help
man date

# check which version of "date" is installed
# ... for Debian/Ubuntu
dpkg --search `which date`
dpkg --status coreutils
# ... for RHEL/CentOS
rpm -qf `which date`
rpm -qi coreutils

Some notes on command substitution. Bash supports both the legacy backticks `someCommand` and the recommended parentheses $(someCommand) form of command substitution. Both styles are used above as they are interchangeable. For related discussions on bash command substitution:


About notesbytom

Keeping technology notes on to free up my mind to solve new problems rather than figuring out the same ones repeatedly :-).
This entry was posted in Linux and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s