使用"bash"或"zsh",具体取决于操作系统和安装



我有一个小函数,可以执行像7za这样的命令行工具。我不知道这个工具是用户安装在哪里的,所以我使用这个功能:

func execute(commandName: String, arguments: [String]) -> String? {
guard var bashCommand = execute(command: "/bin/bash" , arguments: ["-l", "-c", "which (commandName)"]) else { return "(commandName) not found" }   // find path of command itself, e.g. "/usr/local/bin/7za"
bashCommand = bashCommand.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)   // remove newline character at the end
if bashCommand == "" { return nil }  // command not even found! => nil
return execute(command: bashCommand, arguments: arguments)   // now we have: /usr/local/bin/7za e -pPW -o/Users/Shared/File.JPG.7z
}

在 OSX 10.15 上有一个新的 shell zsh。我可以将我的命令从 bash 切换到 zsh,但我的程序应该在任何系统上运行。如何找出要使用的命令?我不想扫描整个硬盘来简单地运行已安装的命令行工具lile "7za"。知道吗?

如何找出要使用的(外壳(命令?

想法:

  1. 使用System.getenv("SHELL")找出用户正在使用的 shell,并使用该 shell。

  2. 使用/bin/sh. 它应该是指向 POSIX 兼容外壳的链接;要么bash要么ksh...或者可能是别的什么。

  3. 运行ls -l /bin/并分析输出,查找与*sh匹配的命令。

  4. 读取/etc/shells文件。

(请参阅如何在 Mac OSX 中检查可用的外壳?

苹果(尚未(表示bash即将消失。 在这个阶段,他们所做的只是默认的外壳是什么。


但我不相信首先有必要这样做:

  • 您无需使用 shell 来运行which。 它应该作为普通(不是 shell 内置(命令提供。 (它是在Linux上...

  • 您不应该需要使用which 7za。 这样做是使用 PATH 变量查找7za命令。 但是,如果您只是运行7za,则会找到并执行完全相同的命令。

  • 如果用户安装7za并将其放在不在 PATH 上的奇怪位置,他们就是反常的。 他们需要更新其 PATH 设置,或将命令放在更常规的位置。

最新更新