I am using the following code to execute a bash command from Swift:
func runCommand(cmd : String, args : String...) -> (output: [String], error: [String], exitCode: Int32) {
var output : [String] = []
var error : [String] = []
let task = NSTask()
task.launchPath = cmd
task.arguments = args
let outpipe = NSPipe()
task.standardOutput = outpipe
let errpipe = NSPipe()
task.standardError = errpipe
task.launch()
let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String.fromCString(UnsafePointer(outdata.bytes)) {
string = string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
output = string.componentsSeparatedByString("\n")
}
let errdata = errpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String.fromCString(UnsafePointer(errdata.bytes)) {
string = string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
error = string.componentsSeparatedByString("\n")
}
task.waitUntilExit()
let status = task.terminationStatus
return (output, error, status)
}
Credit: Get terminal output after a command swift
When I run the function with the following code:
runCommand("/sbin/ifconfig", args: "en1", "|", "grep", "ether")
To simulate running the following command from the shell:
ifconfig en1 | grep ether
That will result in some output like this:
ether xx:xx:xx:xx:xx:xx
I get the following error:
ifconfig: |: bad value
I'm guessing that this is because the commands aren't being combined and the "|" symbol is being interpreted as a direct argument to ifconfig.
Is there a way to simulate this type of shell behaviour (the usage of the "|" symbol to filter the output of a command) from within Swift?