-
-
Save bleeckerj/8978b994f22407598163b6d509e22120 to your computer and use it in GitHub Desktop.
Execute bash commands from Swift 3
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
import Foundation | |
final class Shell | |
{ | |
func outputOf(commandName: String, arguments: [String] = []) -> String? { | |
return bash(commandName: commandName, arguments:arguments) | |
} | |
// MARK: private | |
private func bash(commandName: String, arguments: [String]) -> String? { | |
guard var whichPathForCommand = executeShell(command: "/bin/bash" , arguments:[ "-l", "-c", "which \(commandName)" ]) else { | |
return "\(commandName) not found" | |
} | |
whichPathForCommand = whichPathForCommand.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) | |
return executeShell(command: whichPathForCommand, arguments: arguments) | |
} | |
private func executeShell(command: String, arguments: [String] = []) -> String? { | |
let task = Task() | |
task.launchPath = command | |
task.arguments = arguments | |
let pipe = Pipe() | |
task.standardOutput = pipe | |
task.launch() | |
let data = pipe.fileHandleForReading.readDataToEndOfFile() | |
let output: String? = String(data: data, encoding: String.Encoding.utf8) | |
return output | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment