How can I run a shell script from cocoa application using Swift?
I have a shell script file.sh that I want to run from within my cocoa application. How can I do this using Swift?
Any help appreciated! :)
You can use NSTask
(API reference here) for this.
A NSTask
takes (among other things) a launchPath
which points to your script. It can also take an array of arguments
and when you are ready to launch your task, you call launch()
on it.
So...something along the lines of:
var task = NSTask()
task.launchPath = "path to your script"
task.launch()
As @teo-sartory points out in his comment below NSTask
is now Process
, documented here
The naming and way you call it has changed a bit as well, here is an example of how to use Process
to call ls
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/ls")
try? process.run()
If you want better access to/more control over the output from your invocation, you can attach a Pipe
(documented here).
Here is a simple example of how to use that:
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/ls")
// attach pipe to std out, you can also attach to std err and std in
let outputPipe = Pipe()
process.standardOutput = outputPipe
// away we go!
try? process.run()
//read contents as data and convert to a string
let output = outputPipe.fileHandleForReading.readDataToEndOfFile()
let str = String(decoding: output, as: UTF8.self)
print(str)
You can have a look at:
Hope that helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With