Skip to content

Instantly share code, notes, and snippets.

@finestructure
Created November 27, 2024 07:17
Show Gist options
  • Select an option

  • Save finestructure/8ff2c7d16ab05c73222f28920f74705d to your computer and use it in GitHub Desktop.

Select an option

Save finestructure/8ff2c7d16ab05c73222f28920f74705d to your computer and use it in GitHub Desktop.

Revisions

  1. finestructure created this gist Nov 27, 2024.
    36 changes: 36 additions & 0 deletions Shell.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    // 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
    }
    }