Finder Comments are a mess and unreliable. The best source for this is Howard Oakley's Would you like to Comment or Finder Comment?
Originally Finder Comments were stored in the folder in the .DS_Store
file. Since macOS (I don't know which version) they are often stored in the file's extended attribute com.apple.metadata:kMDItemFinderComment
. But can continue to be in .DS_Store
as well or instead.
The extended attribute belongs to the file and is kept with the file when moving or copying. The Finder Comment in .DS_Store belongs to a conjunction of folder and file; that is broken when you move the file and needs to created afresh in the .DS_Store
of the new folder.
Copying (and duplicating) is hopelessly unreliable for Finder Comments - see Howard Oakley's post.
Note that Spotlight may use Finder Comments stored in either .DS_Store
or as an extended attribute. Both sources are used to populate mdls
's kMDItemFinderComment
. As a result mdls
is not a reliable indicator of what is going on.
A better solution is to use file Comments which are stored as the kMDItemComment
extended attribute (and move with the file) and are sometimes displayed by Finder in Get Info's More Info section. But more reliably shown using xattr
or mdls
and, of course, are available to Spotlight searches,
You say in your final paragraph: If you run xattr file-copy.txt
, you will see that the com.apple.metadata:kMDItemFinderComment
extended attribute itself is preserved, but if you run mdls -name kMDItemFinderComment file-copy.txt
you will see that its value is "".
What I think has happened is that the extended attribute has been copied with the file, but a new blank Finder Comment has been created in .DS_Store
. And then Spotlight has used the blank one in .DS_Store
- and this is what mdls
shows. Remember that mdls
reports metadata in the spotlight index and not directly the content of extended attributes or .DS_Store. It can, for Finder Comments, be populated from either .DS_Store
or from the file's extended attribute.
In conclusion: don't use Finder Comments.
duplicate
a file and the result will have whatever finder comment that the original did. An example command would betell application "Finder" to duplicate file "file.txt" of folder folderPath
, where folderPath would be the path to the file's containing folder. It is possible to call applescript from the shell using theosascript
command. It's a bit quirky but depending upon your specific use case, it might provide a solution.Duplicate
has several options which can be found in its applescript dictionary, and there isman osascript
.