【问题标题】:What is going on when I run a terminal/shell command in Swift?当我在 Swift 中运行终端/shell 命令时发生了什么?
【发布时间】:2017-03-20 21:22:03
【问题描述】:

我花了很多时间研究如何在 Swift 中运行特定的终端/shell 命令。

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

我找到了this question,它似乎向我展示了如何运行命令,但我对 Swift 完全陌生,我想知道每一行的作用。

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

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

【问题讨论】:

  • 大多数时候,顺便说一句,最好生成一个显式的 argv 而不涉及 shell;但是,在这里,您依赖 shell 为您执行 globbing(在调用 rm 之前将 * 扩展为文件名列表)。
  • (将~ 扩展到用户的主目录也是shell 在当前情况下正在执行的一项工作,如果您想不使用它,则需要更换)。跨度>

标签: swift shell nstask


【解决方案1】:
  • /bin/sh 调用 shell
  • -c 将实际的 shell 命令作为字符串
  • rm -rf ~/.Trash/* 删除垃圾箱中的所有文件

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

man rm

【讨论】:

  • 应该指出,这与许多其他语言中的system("rm -rf ~/.Trash/*") 完全相同。
  • 我喜欢垃圾箱中的一些文件。我很高兴我不只是运行它并将它们全部删除。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多