Last active
November 12, 2016 10:46
-
-
Save loganwright/ac333eb122fd623b9e72 to your computer and use it in GitHub Desktop.
Call shell commands from Swift
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
func shell(input: String) -> (output: String, exitCode: Int32) { | |
let arguments = split(input, maxSplit: Int.max, allowEmptySlices: true) { | |
$0 == " " | |
} | |
let task = NSTask() | |
task.launchPath = "/usr/bin/env" | |
task.arguments = arguments | |
task.environment = [ | |
"LC_ALL" : "en_US.UTF-8", | |
"HOME" : NSHomeDirectory() | |
] | |
let pipe = NSPipe() | |
task.standardOutput = pipe | |
task.launch() | |
task.waitUntilExit() | |
let data = pipe.fileHandleForReading.readDataToEndOfFile() | |
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String | |
return (output, task.terminationStatus) | |
} | |
// Example | |
println(shell("git log --oneline").output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line #2 didn't work for Swift 2.0 in Xcode 7.1
Snippet that works: