zumzum
zumzum

Reputation: 20208

run "ls" through NSTask in a Cocoa app not working

I am testing the use of an NSTask because I want to try to run a bunch of commands within my Cocoa application written in Swift that I usually run in Terminal.

In viewDidLoad I have the following code:

    let task = NSTask()
    let pipe = NSPipe()
    task.standardOutput = pipe

    task.launchPath = "/usr/bash"
    task.currentDirectoryPath = dir
    task.arguments = ["ls"]

    let file:NSFileHandle = pipe.fileHandleForReading

    task.launch()
    task.waitUntilExit()

    let data =  file.readDataToEndOfFile()
    let datastring = NSString(data: data, encoding: NSUTF8StringEncoding)
    print("datastring = \(datastring)")

The app runs but I am getting the following error:

Failed to set (contentViewController) user defined inspected property on (NSWindow): launch path not accessible

Can somebody help me understand what I am doing wrong? What I am trying to do now is to run the ls command and then store the result into an array of strings...

Thanks

Upvotes: 1

Views: 950

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90621

Well, for starters, /usr/bash is not the path to the bash executable. You want /bin/bash.

Next, it does not work to invoke /bin/bash ls, which is the equivalent of what you're doing. At a shell, if you want to give a command for bash to process and execute, you would do /bin/bash -c ls. So, you want to set the tasks's arguments to ["-c", "ls"].

However, why are you involving a shell interpreter here, at all? Why not just set the task's launchPath to "/bin/ls" and run the ls command directly? You would either leave the arguments unset, if you just want to list the current working directory's contents, or set it to arguments that you would pass to ls, such as options or a path (e.g. ["-l", "/Applications"]).

Upvotes: 3

Related Questions