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

北战南征 提交于 2019-12-12 10:17:33

问题


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/*"]

回答1:


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()


来源:https://stackoverflow.com/questions/32689013/how-can-i-run-a-terminal-command-in-my-swift-menu-bar-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!