Created
December 7, 2017 16:49
-
-
Save RockfordWei/8b01c4121ab662380ebcb37b2699f85d to your computer and use it in GitHub Desktop.
run bash command
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 | |
#if os(OSX) | |
func bash(command: String) -> String? { | |
let task = Process() | |
task.launchPath = "/bin/bash" | |
task.arguments = ["-c", command] | |
let o = Pipe() | |
task.standardOutput = o | |
task.launch() | |
task.waitUntilExit() | |
let data = o.fileHandleForReading.readDataToEndOfFile() | |
return String(data: data, encoding: .utf8) | |
} | |
#else | |
import Glibc | |
func bash(command: String) -> String? { | |
guard let f = popen(command, "r") else { return nil } | |
defer { pclose(f) } | |
var data = Data() | |
let szbuf = 8192 | |
var size = 0 | |
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: szbuf) | |
defer { buffer.deallocate(capacity: szbuf) } | |
repeat { | |
memset(buffer, 0, szbuf) | |
size = fread(buffer, 1, szbuf, f) | |
if size > 0 { | |
let buf = UnsafeBufferPointer<UInt8>(start: buffer, count: size) | |
data += Array(buf) | |
} | |
} while (size > 0) | |
return String(data: data, encoding: .utf8) | |
} | |
#endif | |
let script = """ | |
cat /etc/hosts | grep 127 | |
""" | |
if let result = bash(command: script) { | |
print(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment