Created
June 27, 2015 22:19
-
-
Save lmedinas/7963ac1985dba4dc60b5 to your computer and use it in GitHub Desktop.
Execute shell commands in swift 2.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
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
task.launchPath = "/bin/sh"
need change totask.launchPath = "/usr/bin/env"