当我在 Swift 中运行终端/外壳命令时发生了什么



我花了相当多的研究来研究如何从 Swift 中运行特定的终端/外壳命令。

问题是,除非我知道它的作用,否则我害怕实际运行任何代码。(我过去在执行终端代码时运气很差。

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

此代码的每一行有什么作用?

let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "rm -rf ~/.Trash/*"]
task.launch()
task.waitUntilExit()
  • /bin/sh调用外壳
  • -c将实际的 shell 命令作为字符串
  • rm -rf ~/.Trash/*删除废纸篓中的每个文件

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

man rm

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

//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"处的过程在这里有更清晰的描述。

最新更新