Giving a file/directory the same modification date as another

For convenience later on, put the following line in your .bashrc file:

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

Execute "source ~/.bashrc" and you're ready to go. If you prefer a script instead, remove the first and last lines -- then prepend "#!/bin/sh"


This will do exactly what you are asking:

touch -r "source_file" "destination_file"


You can get the timestamp of source file using stat in unix timestamp format and then propagate 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 would only work with GNU coreutils which support the unix timestamp using the prefix @ with touch


You have some options:

  • Use touch -t STAMP -m file if you want to change the time
  • Use cp --preserve=timestamps if you're copying the files and want to preserve the time
  • Use touch -r to set the time to a "reference" file

Tags:

Unix

Bash