So I have a shell function that looks like this:
func shell(command: String) -> String {
var output = ""
var error = ""
do {
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
let outputPipe = Pipe()
task.standardOutput = outputPipe
let errorPipe = Pipe()
task.standardError = errorPipe
try task.run()
let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
output = NSString(data: outputData, encoding: String.Encoding.utf8.rawValue)! as String
let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
error = NSString(data: errorData, encoding: String.Encoding.utf8.rawValue)! as String
}
catch let err as NSError{
output = err.localizedDescription
}
return error + "\n" + output + "\n"
}
Into this function I pass my command, which is a Mosquitto Publish command - mosquitto_pub
. Bash doesn't seem to know where this is unless I specify /usr/local/bin/mosquitto_pub
. With that at the start of the command string it works perfectly. The problem is that I don't know that it will be installed at that location for all users so I can't rely on a hard coded path. So I need to find it first and add it to my command string before passing it to the shell function.
In a terminal I can use which mosquitto_pub
and it returns the full path. Excellent. However, when I pass which mosquitto_pub
as a command to the shell function via my swift program, it doesn't return anything. I've also tried type
instead of which
, but it responds with /bin/bash: line 0: type: mosquitto_pub: not found
Anyone know why the terminal can find it normally but not when it's being used from within my Swift program?