Skip to content

Instantly share code, notes, and snippets.

@wearhere
Last active March 5, 2021 01:29
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wearhere/342151ba3791e3eb4ad2 to your computer and use it in GitHub Desktop.
Save wearhere/342151ba3791e3eb4ad2 to your computer and use it in GitHub Desktop.
Shell scripting in Swift, using a proper hashbang and a custom subshell operator.
#!/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