Swift Process-执行命令错误

问题描述:

我正在尝试从用Swift编写的Mac App中执行历史记录"命令.

I'm trying to execute the "history" command from a Mac App written in Swift.

@discardableResult
func shell(_ args: String...) -> Int32 {
    let task = Process()
    task.launchPath = "/bin/bash"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

shell("history")

它总是向我返回此错误:

It always return me this error:

env: history: No such file or directory

怎么了?真的可以在Mac App中使用用户命令行历史记录吗?

What is wrong? It's really possible to work with the user command line history from a Mac App?

使用带有NSTask的某些内置GNU命令(与history一样被认为是交互式的")通常需要设置环境变量,因此shell知道要返回什么,例如:

Using certain built-in GNU commands with NSTask (which are considered "interactive" like history) usually requires that environment variables are set so that the shell knows what to return, for example:

private let env = NSProcessInfo.processInfo().environment

这很困难,因为显然并非所有用户都使用相同的环境变量或外壳程序.一种替代方法是在NSTask中使用不需要建立/设置环境的bash命令:

This can be difficult since not all users obviously are using the same environment variables or shell for that matter. An alternative would be to use bash commands in the NSTask that don't require getting/setting up the environment:

let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", "cat -n ${HOME}/.bash_history"]

let pipe = Pipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)

print(output!)

结果输出应类似于实际shell历史记录的编号格式.

The resulting output should resemble the numbered format of the actual shell history.