Preserve destination timestamp while copying

Hi Guys,

I am trying to copy a file from source to destination, I need to preseve timestamp of destination

cd desitnation
ll file.txt
Aug 17 17:22 file.txt


cp -p source/file.txt destination/

I need to preseve same timestamp after copying

cd desitnation
ll file.txt
Aug 17 17:22 file.txt

It looks to me that you are doing it right. What is the problem?

Also please give OS version and the shell you are using. Also, just in case this is significant (it shouldn't be), are source and destination on the same file system? Use

df <path_to_source>
df <path_to_destination>

to find out.

Andrew

Do you mean that there is an existing file that will get overwritten and you want the time of that? Okay, well you will have to record it and then set the value afterwards.

Something like a combination of stat before the copy and touch afterwards should do it.

How about:-

#!/bin/bash

src_file="/path/to/source/file"             # Define source file to copy
dst_file="/path/to/destin/file"             # Define target file to overwrite and preserve time on

ls -l "${dst_file}"                         # Let's just check it first
file_time=$(stat -c %Y "${dst_file}")       # Get the modification time in seconds since the Epoch

cp "${src_file}" "${dst_file}"              # Copy the file

touch -md "@${file_time}" "${dst_file}"     # Set the modification to the stored value (in seconds)

ls -l "${dst_file}"                         # Let's have a look now

Does that get you near?

Robin

1 Like

perfect yes this is what i was expecting

But can it be done use cp command because sometimes permission wont be there to do touch -md command in destination folder

cp -p source dest

Hi,

This will preserve source timestamp not the destination time stamp.

problem here is i dont have permission to do touch -r or touch -md as suggested bt rbatte1 since my id is not owner for that directory. I am only part of that unix id group . I can able to copy but not able to preserve the timestamp of old one

Would this help?

src_file="/path/to/source/file"
dst_file="/path/to/destin/file"

cp "${src_file}" "${src_file}.tmp"
touch -r "${dst_file}"  "${src_file}.tmp"
mv "${src_file}.tmp" "${dst_file}"

Andrew

If you don't have permissions to set the timestamp, any method you find to accomplish this without getting those permissions will be -- by definition! -- a security exploit. Not going to happen. You'll have to just ask.

What are the exact owners and permissions of the folder? What user / group are you? This will narrow down exactly what you need to ask for.

Do you need to keep the source file and its meta data?
If not,

touch -r dest-file src-file
cp src-file dest-file

create a tar file and restore it in the new directory.