2017-03-20 46 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

我喜歡垃圾桶中的一些文件。我很高興我沒有運行它並全部刪除它們。 –

相關問題