我有一个小函数,它执行像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
}在OSX10.15上有一个新的shell zsh。我可以将命令从bash切换到zsh,但是我的程序应该在任何系统上运行。如何才能找到要使用的命令?我不想扫描整个硬盘,只想运行安装好的命令行工具lile "7za“。有什么想法吗?
发布于 2020-06-06 16:27:54
如何找出使用哪个(shell)命令?
想法:
System.getenv("SHELL")查找用户正在使用的shell,并使用它。/bin/sh。它应该是一个与POSIX兼容的shell的链接;bash或ksh .ls -l /bin/并解析输出,查找与*sh匹配的命令。/etc/shells文件.(见How can I check the available shells in Mac OSX?)
苹果还没有(还)说过bash要走了。在这个阶段,他们所改变的只是默认的shell。
但我不认为有必要这么做:
which。它应该是一个普通的(而不是shell内置的)命令。(它在Linux上.)which 7za。这样做的目的是使用PATH变量查找7za命令。但是,如果您只运行7za.7za并将其放置在一个不位于路径上的奇怪位置,这是完全相同的命令。他们需要更新路径设置,或者将命令放在更常规的位置。。
https://stackoverflow.com/questions/62234237
复制相似问题