Skip to content

Instantly share code, notes, and snippets.

@loganwright
Last active November 12, 2016 10:46
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save loganwright/ac333eb122fd623b9e72 to your computer and use it in GitHub Desktop.
Save loganwright/ac333eb122fd623b9e72 to your computer and use it in GitHub Desktop.
Call shell commands from Swift
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)
@ts95
Copy link

ts95 commented Nov 19, 2015

Line #2 didn't work for Swift 2.0 in Xcode 7.1

Snippet that works:

let arguments = input.characters.split { $0 == " " }.map(String.init)

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