1

I'm trying to build a MacOS app that can run bash commands from GUI input and have fallen at the first hurdle. I've been using this question's answer as a reference but it doesn't seem to work for me. This is my code:

import Foundation

@IBAction func buttonClicked(_ sender: Any) {
       shell("ls")
}

@discardableResult
func shell(_ args: String...) -> Int32 {
    let task = Process()
    task.launchPath = "/Users/myUser/desktop"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

I've seen others asking about this error but they are getting it for slightly different reasons meaning I can't seem to find a fix for my particular instance of the problem.

Any ideas?

EDIT - Would also be great if someone could give me a hint as to how to get the output of the ls command back into my program, to store as a string for example.

SuperHanz98
  • 2,090
  • 2
  • 16
  • 33

1 Answers1

1

For a simple terminal app this is what I used

func shell(_ command: String) -> String {
    let task = Process()
    task.launchPath = "/bin/bash"
    task.arguments = ["-c", command]

    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()

    guard let output = String(data: data, encoding: .utf8) else {
        print("Failed to produce string from \(data)")
        abort()
    }

    return output
}
boidkan
  • 4,691
  • 5
  • 29
  • 43
  • Ohhh, is the launch path the path to bash? I thought it was the path that bash starts up in. That might be why I'm getting the error? – SuperHanz98 Aug 07 '19 at 12:24