Search code examples
xcodeswiftterminalapplescriptosascript

Trouble formatting a string with multiple quotation marks


I am making a NSTask which runs osascript to gracefully quit an application instead of a killall/kill command.

I have this:

let killtask = NSTask()
killtask.launchPath = "/usr/bin/killall"
killtask.launchPath = "/usr/bin/osascript"
killtask.arguments = ["-e","'quit app", ""Transmission"""'"]
killtask.launch()

The troublesome line is the arguments I'm trying to pass.

The command in terminal is like this:

/usr/bin/osascript -e 'quit app "Notes"'

Where am I going wrong? How can I format the arguments so it gets all the single and double quotation marks actually used in the command?

EDIT

Running

killtask.arguments = ["-e \'quit app \"Transmission\"\'"]

Gives me:

0:2: syntax error: A unknown token can’t go here. (-2740)

Solution

  • Here's the correct way to parameterize an AppleScript run via osascript:

    let appName = "Transmission"
    
    let killtask = NSTask()
    killtask.launchPath = "/usr/bin/osascript"
    killtask.arguments = ["-e", "on run {appName}", 
                          "-e", "  quit app appName", 
                          "-e", "end run",
                          appName]
    killtask.launch()