2017-03-20 76 views
0

我花了大量的研究如何在Swift中运行特定的终端/ shell命令。当我在Swift中运行终端/ shell命令时发生了什么?

问题是,我害怕实际运行任何代码,除非我知道它的作用。 (我过去执行终端代码的运气非常糟糕。)

我发现this question这似乎向我展示了如何运行命令,但我对Swift完全陌生,我想知道什么每一行都有。

这段代码的每一行是做什么的?

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

大多数时候,顺便说一下,这是优选的产卵一个明确的argv *无*涉及一个壳的方法;然而,在这里,你依靠shell来为你做globbing(在调用'rm'之前将'*'扩展成文件名列表)。 –

+0

(将'〜'扩展到用户的主目录中也是shell在本例中正在执行的任务,如果没有它,则需要替换)。 –

回答

0

当我写这个问题,我发现我能找到很多问题的答案,所以我决定发布问题并回答它以帮助像我这样的人。

//makes a new NSTask object and stores it to the variable "task" 
let task = NSTask() 

//Tells the NSTask what process to run 
//"/bin/sh" is a process that can read shell commands 
task.launchPath = "/bin/sh" 

//"-c" tells the "/bin/sh" process to read commands from the next arguments 
//"rm -f ~/.Trash/*" can be whatever terminal/shell command you want to run 
//EDIT: from @CodeDifferent: "rm -rf ~/.Trash/*" removes all the files in the trash 
task.arguments = ["-c", "rm -rf ~/.Trash/*"] 

//Run the command 
task.launch() 


task.waitUntilExit() 

在“/ bin/sh的”被描述更加清楚地here.

2
  • /bin/sh调用壳
  • -c花费的实际外壳命令为字符串
  • rm -rf ~/.Trash/*删除每个文件在垃圾箱

-r装置递归的。 -f意味着强制。您可以通过在终端阅读man页面了解更多关于这些选项:

man rm 
+1

我们应该指出,这在许多其他语言中完全等价于'system(“rm -rf〜/ .Trash/*”)'。 –

+0

我喜欢垃圾桶中的一些文件。我很高兴我没有运行它并全部删除它们。 –

相关问题