Skip to content

Instantly share code, notes, and snippets.

@lmedinas
Created June 27, 2015 22:19
Show Gist options
  • Save lmedinas/7963ac1985dba4dc60b5 to your computer and use it in GitHub Desktop.
Save lmedinas/7963ac1985dba4dc60b5 to your computer and use it in GitHub Desktop.
Execute shell commands in swift 2.0
// Credit goes to http://stackoverflow.com/a/26400656/1651253
func execcmd(cmdname: String) -> NSString
{
var outstr = ""
let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", cmdname]
let pipe = NSPipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = NSString(data: data, encoding: NSUTF8StringEncoding) {
print(output)
outstr = output as String
}
task.waitUntilExit()
let status = task.terminationStatus
print(status)
return outstr
}
@dickwu
Copy link

dickwu commented Oct 12, 2016

task.launchPath = "/bin/sh" need change to task.launchPath = "/usr/bin/env"

@cybertunnel
Copy link

depends what you are trying to do, if you are going to use pipe "|" inside your command, I use /bin/sh. I have not been able to successfully pipe commands using /usr/bin/env.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment