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 have file.prev, file.prev2, etc. So I like to add a YYMMDD suffix that shows when the file was last changed.

stat -c %Y gives you the modification time in epoch seconds, then date -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.

Leave a comment