使用 "bash" 或 "zsh" 取决于 OS 和安装
Use of "bash" or "zsh" depending on OS and installation
我有一个小函数可以执行像 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”。有什么想法吗?
How can I find out which (shell) command to use?
想法:
使用System.getenv("SHELL")
找出用户正在使用的shell,并使用它。
使用/bin/sh
。它应该是 link 到 POSIX 兼容的 shell; bash
或 ksh
... 或者其他可能。
运行 ls -l /bin/
并解析输出以查找匹配 *sh
的命令。
读取 /etc/shells
文件。
(见)
Apple 尚未(尚未)表示 bash
即将消失。在这个阶段,他们所改变的只是默认 shell。
但我不认为有必要首先这样做:
您不需要使用 shell 到 运行 which
。它应该作为普通的(不是 shell 内置的)命令提供。 (在 Linux ...)
您应该不需要使用 which 7za
。它的作用是使用 PATH 变量找到 7za
命令。但是如果你只是 运行 7za
.
就会发现并执行完全相同的命令
如果用户安装 7za
并将其放在一个不在 PATH 上的陌生地方,他们就是有悖常理。他们需要更新他们的 PATH 设置,或者将命令放在更常规的地方。
我有一个小函数可以执行像 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”。有什么想法吗?
How can I find out which (shell) command to use?
想法:
使用
System.getenv("SHELL")
找出用户正在使用的shell,并使用它。使用
/bin/sh
。它应该是 link 到 POSIX 兼容的 shell;bash
或ksh
... 或者其他可能。运行
ls -l /bin/
并解析输出以查找匹配*sh
的命令。读取
/etc/shells
文件。
(见
Apple 尚未(尚未)表示 bash
即将消失。在这个阶段,他们所改变的只是默认 shell。
但我不认为有必要首先这样做:
您不需要使用 shell 到 运行
which
。它应该作为普通的(不是 shell 内置的)命令提供。 (在 Linux ...)您应该不需要使用
which 7za
。它的作用是使用 PATH 变量找到7za
命令。但是如果你只是 运行7za
. 就会发现并执行完全相同的命令
如果用户安装
7za
并将其放在一个不在 PATH 上的陌生地方,他们就是有悖常理。他们需要更新他们的 PATH 设置,或者将命令放在更常规的地方。