当我 运行 在 Swift 中执行 terminal/shell 命令时发生了什么?

What is going on when I run a terminal/shell command in Swift?

我花了很多时间研究如何从 Swift.

中 运行 特定的 terminal/shell 命令

问题是,我不敢 运行 任何代码,除非我知道它的作用。 (我过去执行终端代码时运气很差。)

我发现 似乎向我展示了如何执行 运行 命令,但我对 Swift 完全陌生,我想知道每一行的作用。

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

let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "rm -rf ~/.Trash/*"]
task.launch()
task.waitUntilExit()
  • /bin/sh 调用 shell
  • -c 将实际的 shell 命令作为字符串
  • rm -rf ~/.Trash/* 删除回收站中的所有文件

-r表示递归。 -f表示被迫。您可以通过阅读终端中的 man 页面来了解有关这些选项的更多信息:

man rm

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

//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.