An easy way to name files with year, date and time

Whether you’re creating log files of any crontab job, or “scheduled task” (to use windows parlance) or if you keep a journal or any other reason, you may want to name a file with today’s current year, date & time.

Assuming you were just doing a simple command like ‘ls’, an easy way to dump the output to a file with the full date and time would be:

ls >>`date +"%Y%m%d%H%M%S"`

The double arrow >> simply says to append the output to the file, instead of overwriting it (in case it already exists). Note that this filename goes all the way down to the second, so it’s highly unlikely the file would ever be overwritten by another job in crontab, even if you only used a single > arrow.

To rename an existing file and append the date, just type:

mv ./filename ./filename.`date +"%Y%m%d%H%M%S"`

This will add a dot and then the year, month day and time.

If you were keeping a simple text journal, just run your favorite command line text editor (like nano) and simple save the file with this filename:

`date +"%Y%m%d%H%M%S"`

This will give you a filename that looks like: 20120223073844 which is literally the year, month, day, hour, minute and second that the file was saved. if you want some breaks in there for readability save the file as:

`date +"%Y_%m_%d__%H_%M_%S"`

Which would look like: 2012_02_23__07_38_44. The hours will be in 24-hour mode, though you could use %r for an AM/PM mode, it auto-adds :colons: to the time, which can make dealing with filenames rather difficult.

Note that if you try this in a graphical editor, it will actually save the file literally as `date +”%Y_%m_%d__%H_%M_%S”` instead of using the meaning of those variables, so this will only work in a text-based editor such as nano, or vi but wouldn’t work with gedit.

Here’s a reference for date and time variables.