0

I'm trying to run terminal commands/scripts from my application, all is working fine however when a command is wrong and can not execute I get something like this:

enter image description here

but this "/bin/bash: line..." string is not in my output string I get from the task, is there any way of getting these errors in my app or get notified in any way they occurred?

my code

    // Create a new task
    let task: Process = Process()
    task.environment = env
    task.launchPath = "/usr/bin/env"
    task.arguments = ["/bin/bash", "-c", command.scriptCode]

    // Assign output pipes
    let pipe: Pipe = Pipe()
    let outHandle: FileHandle = pipe.fileHandleForReading
    task.standardOutput = pipe

    outHandle.readabilityHandler = { pipe in
        if let line = String(data: pipe.availableData, encoding: String.Encoding.utf8) {
            if line.contains("command not found") {
                // never triggered 
            } else {
                print("New ouput: \(NSDate() )\(line)")
            }
        } else {
            print("Error decoding data: \(pipe.availableData)")
        }
    }
Steven B.
  • 1,429
  • 2
  • 19
  • 38
  • 1
    The bash would write the messages to stderr, so you can capture `task.standardError` in the same way as you capture `task.standardOutput`. – Martin R Jun 14 '17 at 18:46
  • Thanks working as expected, Xcode did only autocomplete the standardOutput :o – Steven B. Jun 14 '17 at 18:50

1 Answers1

2

The thing you are looking for is standardError property of NSTask or Process class. Assign pipe to this property just like you do with standardOutput.

toma
  • 1,471
  • 12
  • 20