Hi I am looking for a command on macOS 11.6 to copy the access time from source file to destination file.
The access time source file must not be updated.
Even simpler!
touch -a -r sourcefile destinationfile
This only changes access time, while my other example changed both access and modification time on the destination. See man touch
for details.
Note: On macOS 11.6, 10.14 (and probably earlier), if the touched file is non-zero length and in a folder indexed by Spotlight, Spotlight will update the access time to the current time soon after the access time is set. Preferences/Spotlight/Privacy can be used to exclude folders from Spotlight indexing.
This script should do the trick:
#!/bin/sh
if [ $# -ne 2 ]; then
echo "Usage: $(basename $0) source destination"
exit 1
fi
FMT="%Y%m%d%H%M.%S"
atime=$(stat -f %Sa -t "$FMT" "$1")
if [ -n "$atime" ]; then
touch -t "$atime" "$2"
fi
It copies the access time using stat, and writes using touch.
-a
option, as in touch -a -t "$atime" "$2"
. Also, the note given in MichaelR's other answer should apply to this answer.
Commented
Sep 18, 2021 at 12:12
The command
cp -p source destination
will do the job.
From man pages :
-p Cause cp to preserve the following attributes of each source file in the copy: modification time, access time, file flags, file mode, user ID, and group ID, as allowed by permissions. Access Control Lists (ACLs) and Extended Attributes (EAs), including resource forks, will also be preserved.