Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a shell script from cocoa application using Swift?

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

like image 697
iSebbeYT Avatar asked Dec 02 '22 13:12

iSebbeYT


1 Answers

Pre Swift 3

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()

Post Swift 3

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)

Would you like to know more

You can have a look at:

  • an example gist here
  • This answer (in Objective C)
  • This tutorial from Ray Wenderlich
  • This article by Paul Hudson

Hope that helps you.

like image 110
pbodsk Avatar answered Mar 07 '23 21:03

pbodsk