Providing a file / directory with the same modification date as another

How can I "copy" the date and time of a change from one file / directory to another on Unix based systems?

+8
unix bash
source share
5 answers

You have several options:

  • Use touch -t STAMP -m file if you want to change the time
  • Use cp --preserve=timestamps if you are copying files and want to save time.
  • Use touch -r to set the time to a "reference" file
+14
source share

You can get the timestamp of the source file using stat in timestamp format in unix format and then transfer it to the destination file using touch -d

 src_file=/foo/bar dst_file=/bar/baz touch -d @$(stat -c "%Y" "$src_file") "$dst_file" 

NOTE. This will only work with GNU coreutils that support unix timestamps using the @ prefix with touch

+1
source share

Further, for convenience, add the following line to the .bashrc file:

 cptimestamp() { if [ -z $2 ] ; then echo "usage: cptimestamp <sourcefile> <destfile>" exit fi touch -d @$(stat -c "%Y" "$1") "$2" } 

Run "source ~ / .bashrc" and you are ready to go. If you prefer a script instead, delete the first and last lines - then add "#! / Bin / sh"

+1
source share

Use touch ; it contains several optional flags that allow you to set such attributes.

0
source share

If you use cp, use the -p option to save the modification time. cp -p

0
source share

All Articles