I'm trying to execute a command and would like to put the date and time in the output file name.
Here is a sample command I'd like to run.
md5sum /etc/mtab > 2016_4_25_10_30_AM.log
The date time format can be anything sensible with underscores. Even UTC if the AM and PM can't be used.
Best Answer
If you want to use the current datetime as a filename, you can use
date
and command substitution.This results in the file
2016_04_25_10_30_AM.log
(although, with the current datetime) being created with the md5 hash of/etc/mtab
as its contents.Please note that filenames containing 12-hour format timestamps will probably not sort by name the way you want them to sort. You can avoid this issue by using 24-hour format timestamps instead.
If you don't have a requirement to use that specific date format, you might consider using an ISO 8601 compliant datetime format. Some examples of how to generate valid ISO 8601 datetime representations include:
If you want "safer" filenames (e.g., for compatibility with Windows), you can omit the colons from the time portion.
Please keep in mind that the above examples all assume local system time. If you need a time representation that is consistent across time zones, you should specify a time zone offset or UTC. You can get an ISO 8601 compliant time zone offset by using "%z" in the format portion of your
date
call like this:You can get UTC time in your
date
call by specifying the-u
flag and adding "Z" to the end of the datetime string to indicate that the time is UTC like this: