将bash命令相互组合

时间:2015-04-09 21:49:10

标签: bash shell swift

我使用以下代码从Swift执行bash命令:

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)
}

信用:Get terminal output after a command swift

当我使用以下代码运行该函数时:

runCommand("/sbin/ifconfig", args: "en1", "|", "grep", "ether")

模拟从shell运行以下命令:

ifconfig en1 | grep ether

这会产生如下输出:

ether xx:xx:xx:xx:xx:xx 

我收到以下错误:

ifconfig: |: bad value

我猜这是因为没有组合命令和“|”符号被解释为 ifconfig 的直接参数。

有没有办法在Swift中模拟这种类型的shell行为(使用“|”符号来过滤命令的输出)?

1 个答案:

答案 0 :(得分:0)

解决了nhgrif的评论:Combine bash commands with each other