Move a file, replacing existing (if any), ideally by putting existing in the trash

applescriptfinderterminaltrash

I am trying to find a way to automatically (without user intervention) move a file from A to B, replacing B if it exists, ideally by putting the existing copy of B into the appropriate Trash folder.

This will be done in a shell script. Eventually A and B will beed to be $VARIABLES like this:

/usr/bin/osascript <<EOT
tell application "Finder"
    move POSIX file "$SOURCE" to POSIX file “$DEST" with replacing
end tell
EOT

but I can’t even get this to work without variables, such as this:

/usr/bin/osascript <<EOT
tell application "Finder"
    move POSIX file "/Users/luomat/Desktop/1.txt" to POSIX file "/Users/luomat/Desktop/2.txt" with replacing
end tell
EOT

I took that syntax pretty much directly from Stackoverflow 14058061 but I get this result:

24:132: execution error: Finder got an error: AppleEvent handler failed. (-10000)

I also came across a MacTech article which suggested using replacing true so I tried:

/usr/bin/osascript <<EOT
tell application "Finder"
    move POSIX file "/Users/luomat/Desktop/1.txt" to POSIX file "/Users/luomat/Desktop/2.txt" replacing true
end tell
EOT

but it still says:

24:132: execution error: Finder got an error: AppleEvent handler failed. (-10000)

Please note that stackoverflow #12708195 I am not trying to prompt the user to do this, but ideally would like it to happen ‘automagically’ as the kids say.

So… what am I doing wrong and/or missing? Trying to Google for information on error code (-10000) pretty much tells me that it means “AppleScript failed” which isn’t all that helpful.

Best Answer

I need to do some more research to get this right. I feel like its close, but applescript still doesn't like it. Maybe it will give you some ideas until I get back here to give it another shot. Btw this is going to be so much easier when you are using the choose file dialog.

heres my non-working (yet) attempt. If you don't be me to it ill try to finish the solution tomorrow.

# 1. get desktop folder
set desktopFolder to (((path to desktop from user domain) as string)) as alias


# 2.set source file
tell application "Finder" to ¬
set theFile to ((path to file "1.text" of folder (desktopFolder)) as string) as   alias


# 3.set destination file
tell application "Finder" to ¬
set theDestination to ((path to file "2.text" of folder (desktopFolder)) as string) as alias



# 4.make it happen
tell application "Finder" to move theFile to theDestination with replacing