Image for post
Image for post
Photo by Jay Ruzesky on Unsplash

Linux: Rename a file appending a timestamp one-liner

Scenario: We have a script that runs every day, this script generates a file ( 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.


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– if the command executed at Dec-31–2020 21:55:00

Pitfall: the first time you will run this command probably will exit with a code != 0 this is because will not exist yet! and this might be a problem if you run the command combined with other commands like this

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 following

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 :)

Written by

DevOps engineer, loves Linux, Python, cats and Amiga computers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store