2
votes

I am trying to run the following two bash commands in a Cocoa app:

defaults write com.apple.finder CreateDesktop false
killall Finder

Using NSTask, I have the following Swift code to execute the command when a button is clicked:

let commands = ["-c", "defaults write com.apple.finder CreateDesktop false",
                "-c", "killall Finder"]

let task = NSTask()
task.launchPath = "/bin/bash"
task.arguments = commands
task.launch()

I get no errors when running the code. But nothing actually happens when the button is clicked. Any suggestions?

1

1 Answers

2
votes

Are you sure nothing happens? You cannot pass multiple -c arguments to Bash like that, but mine does execute the first command when I try.

$ bash -c 'echo foo' -c 'echo bar'
foo

In this particular case, the workaround is simple;

$ bash -c 'echo foo; echo bar'
foo
bar

More generally, the individual commands you were passing in to Bash do not need a shell at all. To just kill Finder,

task.launchPath = "/usr/bin/killall"
task.arguments = [ "Finder" ]

but given that you do have multiple commands, running them from a shell actually makes sense.

let task = NSTask()
task.launchPath = "/bin/bash"
task.arguments = ["-c",
     "defaults write com.apple.finder CreateDesktop false; killall Finder"]
task.launch()