-
-
Save felipeg48/495cc93998cc39cef897 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/xcrun swift -i -sdk /Applications/Xcode6-Beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk | |
// | |
// shell.swift | |
// | |
// Shell scripting in Swift, using a proper hashbang and a custom subshell operator. | |
// To run: `chmod +x shell.swift && ./shell.swift`. | |
// | |
// If you edit this in Xcode, ignore the error on the hashbang line. | |
// To play around with this in a playground, comment out the hashbang line. | |
// | |
// Created by Jeffrey Wear on 6/8/14. | |
// | |
// | |
import Foundation | |
/** | |
Returns the standard output and exit status of running _command_ in a subshell. | |
The operator will block (by polling the current run loop) until _command_ exits. | |
@param command An absolute path to an executable, optionally followed by one or more arguments. | |
@return (output, exitStatus) The output and exit status of the executable invoked | |
by _command_. | |
*/ | |
operator prefix > {} | |
@prefix func > (command: String) -> (output: String, exitStatus: Int) { | |
let tokens = command.componentsSeparatedByString(" ") | |
let launchPath = tokens[0] | |
let arguments = tokens[1..tokens.count] | |
let task = NSTask() | |
task.launchPath = launchPath | |
task.arguments = Array(arguments) | |
let stdout = NSPipe.pipe() | |
task.standardOutput = stdout | |
task.launch() | |
task.waitUntilExit() | |
let outData = stdout.fileHandleForReading.readDataToEndOfFile() | |
let outStr = NSString(data: outData, encoding: NSUTF8StringEncoding) | |
return (outStr, Int(task.terminationStatus)) | |
} | |
// Note that nothing is printed here; | |
// '>' captures and returns the output of the command. | |
assert((>"/bin/echo -n Hello world").exitStatus == 0) | |
// Now we capture the output. | |
let command = "/bin/echo -n Hello world" | |
let (output, exitStatus) = >command | |
println("'\(command)' exited with status \(exitStatus) and output '\(output)'.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment