Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run shell command in swift?

Tags:

macos

swift

I'm doing a macOS app, trying to run shell command in child process. I'll get an error Couldn't posix_spawn: error 13 if I don't set launchPath to /usr/bin/env, why is it like this? How can I run shell command in other path?

class Helper {
    static func shell(launchPath path: String, arguments args: [String]) -> String {
        let task = Process()
        task.launchPath = path
        task.arguments = args

        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!)
    }
}

let res = Helper.shell(launchPath: "/Users/myUserName", arguments: ["ls"]) //error
like image 780
vincentf Avatar asked Jan 22 '18 06:01

vincentf


1 Answers

It's possible to access to a path like /Users/myName/myWorkspace, but you have first, to disable the app sandbox doing so:

enter image description here

If you want to run ls in a custom directory, you might try this example:

let res = Helper.shell(launchPath: "/bin/ls", arguments: ["/Users/myUserName/myworkspace"])
print("*** ls ***:\n\(res)")

in my case I have the following output:

*** ls ***:
file1.txt
file2.txt
file3.txt
like image 53
Andrea Mugnaini Avatar answered Sep 25 '22 21:09

Andrea Mugnaini