4

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

in the same script, how can I export dates? "export HISTTIMEFORMAT=\'%m/%d - %H:%M:%S: \'" return me the same 'No such file or directory '
1

The history command is an internal bash command. As such, the correct syntax is:

$ bash -C history

In your shell function:

task.arguments = ["-C"] + args

1 Comment

@Marco There was a typo... please try again now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.