Copy or move files using AppleScript

When copying or moving files using the shell, although the tags (red, orange, etc.) are reliably preserved, the comments are often lost. This is why, if you need to copy or move files using scripts, it is much better to do it by envoking AppleScript for this.

Here is a test directory tree:

~/
|- aaa/
   |- bbb/
   |  |- ccc/
   |  |- foo.ext
   |
   |- ddd/
      |- eee/

And below are two ways to copy foo.ext by envoking AppleScript: using the -e option and using the heredoc notation.

I ask here to help me (and other people who will find it useful), to improve either of the two versions so that it can be used like

cp-or-mv-with-applescript.sh <source> <target>

The first version

  • It is essentially 3 scripts within 1
  • Comments must be removed
osascript -l AppleScript \
-e 'set currentFolder to do shell script "pwd"' \
-e 'set currentFolder to ((POSIX file currentFolder) as text)' \
-e 'tell application "Finder"' \
\
  # to the same folder (foo.ext -> foo copy.ext) \
  -e 'duplicate file (currentFolder & "foo.ext")' \
\
  # to ~/aaa/bbb/ccc/ \
  -e 'duplicate file (currentFolder & "foo.ext") to folder (currentFolder & "ccc:")' \
\
  # to ~/aaa/ddd/ \
  -e 'set parentFolder to ((container of folder currentFolder) as text)' \
  -e 'duplicate file (currentFolder & "foo.ext") to folder (parentFolder & "ddd:")' \
\
  # to ~/aaa/ \
  -e 'set parentFolder to ((container of folder currentFolder) as text)' \
  -e 'duplicate file (currentFolder & "foo.ext") to folder parentFolder' \
\
-e 'end tell'

The second version

# to ~/aaa/bbb/ccc/
osascript << SCRIPT
set currentFolder to "$(pwd)" as POSIX file as text
tell application "Finder"
  duplicate file (currentFolder & "foo.ext") to folder (currentFolder & "ccc:")
end tell
SCRIPT
# to ~/aaa/ddd/
osascript << SCRIPT
set currentFolder to "$(pwd)" as POSIX file as text
set parentFolder to "$(dirname $PWD)" as POSIX file as text
tell application "Finder"
  duplicate file (currentFolder & "foo.ext") to folder (parentFolder & "ddd:")
end tell
SCRIPT
# or
osascript << SCRIPT
set currentFolder to "$(pwd)" as POSIX file as text
tell application "Finder"
  set parentFolder to (container of folder currentFolder) as text
  duplicate file (currentFolder & "foo.ext") to folder (parentFolder & "ddd:")
end tell
SCRIPT

I wonder if you tried ditto? I think it should preserve everything although I’m not exactly sure by now.

Hello, Leo. Yes, I tried, and no, it doesn’t. I remember ditto failed at the exactly same circumstances as cp or mv. I don’t remember the circumstances themselves (it was December), but they are clearly reproducable and occur in real-life usage very often.