Automator AppleScript – Fix Error with Automator AppleScript ‘do shell script’ Call

applescriptautomatorssh

I have a simple automator app that runs a simple script. It uses ssh to open a file on the local machine, MachineA, with an app on the remote machine, MachineB, and logs the ssh call.

on run {input, parameters}
    repeat with fn in input
        set fn to POSIX path of fn
        set fn to "/Volumes/MachineA" & fn
        set fn to "\"/usr/bin/open -a /Applications/Preview.app " & fn & "\""
        set cmd to "ssh -x MachineB.local " & quoted form of fn
        do shell script "echo " & cmd & " >> ~/cmd.log"
        do shell script cmd
    end repeat
end run

The log output is:

ssh -x MachineB.local "/usr/bin/open -a /Applications/Preview.app /Volumes/MachineA/Users/<USER>/Documents/<FOLDER>/<FILE>.pdf"

When I use the app to open a file (drag & drop), an error is thrown.

error message

However, if I copy the output in the log file to the command line, success, the file is opened on the remote machine. Why the difference?

Best Answer

I haven't tested this, but it looks like you have too many levels of quotes there. You manually put double-quotes around the command to be run over ssh (in the set fn to "\"/usr/bin/open ... & "\"" line), and then use quoted form of fn, which adds another level of quotes. It looks fine when you echo it, but that's because the shell parses & removes one level of quotes before passing to the echo command.

Also, if the file path contains spaces or other funny characters, those need to be quoted (but only that path part, not the entire command). Try this instead:

on run {input, parameters}
    repeat with fn in input
        set fn to POSIX path of fn
        set fn to "/Volumes/MachineA" & fn
        set fn to "/usr/bin/open -a /Applications/Preview.app " & quoted form of fn
        set cmd to "ssh -x MachineB.local " & quoted form of fn
        do shell script "echo " & quoted form of cmd & " >> ~/cmd.log"
        do shell script cmd
    end repeat
end run