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
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
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
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.