2

I'm looking for a way to run terminal commands from in Swift (macOS). I came accross this post, but I can't seem to get any of the solutions to work. I am trying to shut down my mac from my app as you can do from terminal (osascript -e 'tell app "loginwindow" to «event aevtrsdn»'), but whenever I do it, I get error: Couldn't posix_spawn: error 13.

I am using this code:

func shell(launchPath: String, arguments: [String] = []) -> (String? , Int32) {
        let task = Process()
        task.launchPath = launchPath
        task.arguments = arguments

            let pipe = Pipe()
            task.standardOutput = pipe
            task.standardError = pipe
            task.launch()
            let data = pipe.fileHandleForReading.readDataToEndOfFile()
            let output = String(data: data, encoding: .utf8)
            task.waitUntilExit()
            return (output, task.terminationStatus)
        }

and I call it from this:

let z = shell(launchPath: "/usr/bin/osascript", arguments: ["-e", "\'tell app \"loginwindow\" to «event aevtrsdn»\'"])

Any help?

Community
  • 1
  • 1
Saransh Malik
  • 726
  • 1
  • 4
  • 16

1 Answers1

1

Your code is correct, but you must not enclose the second argument in single-quotes:

let z = shell(launchPath: "/usr/bin/osascript", arguments: ["-e", "tell app \"loginwindow\" to «event aevtrsdn»"])

That is only necessary when executing a program from the shell. Process passes the given arguments directly to the spawned executable, without interpretation by a shell.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382