如何在我的 swift 菜单栏应用程序中运行终端命令? [英] 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
我真的不明白为什么我会收到这个错误,因为我可以打开终端并运行/bin/sh,然后输入 rm -rf ~/.Trash/* 并且它按预期工作.
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.
编辑
我尝试将命令更改为此,但没有任何反应:
I have tried to change the commands to this but nothing happens:
task.launchPath = "/bin/rm"
task.arguments = ["-rf", "~/.Trash/*"]
推荐答案
使 /bin/sh 从需要传递 -c 参数的命令行字符串中读取.
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()
这篇关于如何在我的 swift 菜单栏应用程序中运行终端命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!