Skip to content

Instantly share code, notes, and snippets.

@bleeckerj
Forked from andreacipriani/Bash.swift
Created July 16, 2018 21:59
Show Gist options
  • Save bleeckerj/8978b994f22407598163b6d509e22120 to your computer and use it in GitHub Desktop.
Save bleeckerj/8978b994f22407598163b6d509e22120 to your computer and use it in GitHub Desktop.
Execute bash commands from Swift 3
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