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
What is wrong? It's really possible to work with the user command line history from a Mac App?
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
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!)
The resulting output should resemble the numbered format of the actual shell history.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With