Unix & Linux Asked by visc on February 2, 2021
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.
Just adding illustration of the (complicated) syntax needed to insert a chosen date string into the middle of a path/filename. As this is usable with any command, I show for copying a file to a new location with timestamped addition to the filename:
cp filename.txt /path/to/copyfile/$(date +"%FT%H%M")-newfilename.txt
Note that quotes around the expression for the newfilename are not required, despite the presence of a space in date +"%F . Indeed, inclusion of such quotes prevents the command from working if included as a crontab line, due to the way shell parsing works.
Answered by ExperiMentor on February 2, 2021
If you want to use the current datetime as a filename, you can use date
and command substitution.
$ md5sum /etc/mtab > "$(date +"%Y_%m_%d_%I_%M_%p").log"
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:
$ date +"%FT%T"
2016-04-25T10:30:00
$ date +"%FT%H%M%S"
2016-04-25T103000
$ date +"%FT%H%M"
2016-04-25T1030
$ date +"%Y%m%dT%H%M"
20160425T1030
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:
$ date +"%FT%H%M%z"
2016-04-25T1030-0400
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:
$ date -u +"%FT%H%MZ"
2016-04-25T1430Z
Answered by Ryan on February 2, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP