Skip to content

Instantly share code, notes, and snippets.

@heckj
Forked from finestructure/Shell.swift
Created November 27, 2024 07:22
Show Gist options
  • Save heckj/b209c1be96f389ced05ae75a19b6dcdf to your computer and use it in GitHub Desktop.
Save heckj/b209c1be96f389ced05ae75a19b6dcdf to your computer and use it in GitHub Desktop.
Tim's Process helpers
// Via Tim Condon
@discardableResult
func shell(_ args: String..., returnStdOut: Bool = false, stdIn: Pipe? = nil) throws -> (Int32, Pipe) {
return try shell(args, returnStdOut: returnStdOut, stdIn: stdIn)
}
@discardableResult
func shell(_ args: [String], returnStdOut: Bool = false, stdIn: Pipe? = nil) throws -> (Int32, Pipe) {
let task = Process()
task.executableURL = URL(fileURLWithPath: "/usr/bin/env")
task.arguments = args
let pipe = Pipe()
if returnStdOut {
task.standardOutput = pipe
}
if let stdIn = stdIn {
task.standardInput = stdIn
}
try task.run()
task.waitUntilExit()
return (task.terminationStatus, pipe)
}
extension Pipe {
func string() -> String? {
let data = self.fileHandleForReading.readDataToEndOfFile()
let result: String?
if let string = String(data: data, encoding: String.Encoding.utf8) {
result = string
} else {
result = nil
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment