Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Process - execute command error

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?

like image 333
Marco Avatar asked Oct 27 '25 07:10

Marco


1 Answers

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.

like image 103
l'L'l Avatar answered Oct 28 '25 20:10

l'L'l