How to save and restore file's created/modified dates?

I've copied a bunch of files from one server to the other, and now the files' dates are reset to current.

How to backup files' dates on old server and restore the them on the new one (without re-transferring all files)?


Solution 1:

Here are scripts to save and restore all {c,n,a}times of files and directories:

Save:

find / -mount -print0 | perl -ne 'INIT{ $/ = "\0"; use File::stat;} chomp; my $s = stat($_); next unless $s; print $s->ctime . "/" . $s->mtime . "/" . $s->atime ."/$_\0"; ' > dates.dat

Restore:

cat dates.dat |  perl -ne 'INIT{ $/ = "\0";} chomp; m!^([0-9]+)/([0-9]+)/([0-9]+)/(.*)!s or next; my ($ct, $mt, $at, $f) = ($1, $2, $3, $4); utime $at, $mt, $f;'

It does not set ctime (inote-change time) although.

Solution 2:

I have a Python script for doing this at https://github.com/robertknight/mandrawer/blob/master/save-file-attrs.py

On the original server run:

save-file-attrs.py save scp .saved-file-attrs <user>@<dest-server>:<path>

On the destination server run:

cd <path> save-file-attrs.py restore

This will restore the file attributes.

Solution 3:

You can use stat to get the dates on the source and touch to modify them on the target.

Solution 4:

If file names are not too weird, and I only need to restore mtime, I use this quick & dirty solution:

find . -type f -exec stat -c 'touch --no-create -d "%y" "%n"' {} \;

This creates a script on the source, and that script can be run on the destination to restore the mtime timestamps.