Skip to content

Instantly share code, notes, and snippets.

@SLboat
Forked from andreacipriani/Bash.swift
Created December 27, 2019 13:25
Show Gist options
  • Save SLboat/cca0ad6d4989af1ff43e38656622f8a5 to your computer and use it in GitHub Desktop.
Save SLboat/cca0ad6d4989af1ff43e38656622f8a5 to your computer and use it in GitHub Desktop.
Execute shell/bash commands from Swift
import Foundation
protocol CommandExecuting {
func execute(commandName: String) -> String?
func execute(commandName: String, arguments: [String]) -> String?
}
final class Bash: CommandExecuting {
// MARK: - CommandExecuting
func execute(commandName: String) -> String? {
return execute(commandName: commandName, arguments: [])
}
func execute(commandName: String, arguments: [String]) -> String? {
guard var bashCommand = execute(command: "/bin/bash" , arguments: ["-l", "-c", "which \(commandName)"]) else { return "\(commandName) not found" }
bashCommand = bashCommand.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
return execute(command: bashCommand, arguments: arguments)
}
// MARK: Private
private func execute(command: String, arguments: [String] = []) -> String? {
let process = Process()
process.launchPath = command
process.arguments = arguments
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: String.Encoding.utf8)
return output
}
}
let bash: CommandExecuting = Bash()
if let lsOutput = bash.execute(commandName: "ls") { print(lsOutput) }
if let lsWithArgumentsOutput = bash.execute(commandName: "ls", arguments: ["-la"]) { print(lsWithArgumentsOutput) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment