Shell: Create a file backup with modification date as suffix
source link: https://proinsias.github.io/til/shell-create-a-file-backup-with-modification-date-as-suffix/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Francis T. O'Donovan
Senior Data Science Manager at Hospital IQ – Planet discoverer, researcher, developer, geek.
Shell: Create a file backup with modification date as suffix
less than 1 minute read
When I go to change a configuration file I always like to make a backup first. You can use
cp -p
to preserve the modification time, but it gets confusing to havefile.prev
,file.prev2
, etc. So I like to add aYYMMDD
suffix that shows when the file was last changed.
stat -c %Y
gives you the modification time in epoch seconds, thendate -d @
converts that to whatever format you specify in your+format
string.
For example:
> ls -l
-rw-r--r-- 1 root root 0 Dec 31 2018 file
> cp file file.$(date -d @$(stat -c '%Y' file) "+%Y%m%d")
> ls -l
-rw-r--r-- 1 root root 0 Dec 31 2018 file
-rw-r--r-- 1 root root 0 Dec 31 2018 file.20181231
You can simplify the copy command using:
cp file{,.$(date -d @$(stat -c '%Y' file) "+%Y%m%d")}
Via commandlinefu.com.
Categories: til
Updated: June 28, 2022
You May Also Enjoy
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK