A command to copy the access time of files on macOS 11.6 Big Sur
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.
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.