bandoy123
bandoy123

Reputation: 243

How can I run a terminal command in my swift menu bar app?

I have made a menu bar app and I want this command to be run on press

rm -rf ~/.Trash/*

The code I currently have is this:

@IBAction func toggleClicked(sender: NSMenuItem) {

    let task = NSTask()
    task.launchPath = "/bin/sh"
    task.arguments = ["rm", "-rf", "~/.Trash/*"]
    task.launch()
    task.waitUntilExit()

}

But when I run this, I get the following error:

/bin/rm: /bin/rm: cannot execute binary file

I dont really understand why I'm getting this error since I can open terminal and run /bin/sh, then enter in rm -rf ~/.Trash/* and it works as expected.

EDIT

I have tried to change the commands to this but nothing happens:

    task.launchPath = "/bin/rm"
    task.arguments = ["-rf", "~/.Trash/*"]

Upvotes: 1

Views: 501

Answers (1)

Tomas Camin
Tomas Camin

Reputation: 10086

To make /bin/sh read from the command line string you need to pass the -c argument.

Your code needs to be changed as follows:

    let task = NSTask()
    task.launchPath = "/bin/sh"
    task.arguments = ["-c", "rm -rf ~/.Trash/*"]
    task.launch()
    task.waitUntilExit()

Upvotes: 1

Related Questions