Linux: Rename a file appending a timestamp one-liner
Scenario: We have a script that runs every day, this script generates a file (report.zip) which always have the same name, this causes the…
Scenario: We have a script that runs every day, this script generates a file (report.zip) which always have the same name, this causes the previous day file to be overwritten. We need a way to take a backup of this file before generating a new one.
Solution:
We can combine mv and date command , date generates a format string with the following format: %Y_%m_%d-%H_%M_%S, so the file will have the form of: report-2020_12_31–21_55_00.zip if the command executed at Dec-31–2020 21:55:00mv report.zip report-`date +%Y_%m_%d-%H_%M_%S`.zip
Pitfall: the first time you will run this command probably will exit with a code != 0 this is because report.zip will not exist yet! and this might be a problem if you run the command combined with other commands like thismv ./report/report.zip ./report/report-`date +%Y_%m_%d-%H_%M_%S`.zip && find ./report -maxdepth 1 -name '*.csv' | zip ./report/report.zip -@
The commands after mv will not be executed because using && means for linux that i will execute the next command only if the previous is successful (exit code 0), since it might be normal not to have an initial file we can do the followingmv ./report/report.zip ./report/report-`date +%Y_%m_%d-%H_%M_%S`.zip; find ./report -maxdepth 1 -name '*.csv' | zip ./report/report.zip -@
using ; and not using && means that we don't care for the exit code of mv, just continue to the next command.
I hope you found my article useful :)