且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查命令是否存在于 shell 脚本中?

更新时间:2023-11-25 22:09:34

通常,这取决于您的 shell,但如果您使用 bash、zsh、ksh 或 sh(由 dash 提供),以下内容应该有效:

In general, that depends on your shell, but if you use bash, zsh, ksh or sh (as provided by dash), the following should work:

if ! type "$foobar_command_name" > /dev/null; then
  # install foobar here
fi

对于真正的安装脚本,您可能希望确保在存在别名 foobar 的情况下 type 不会成功返回.在 bash 中,您可以执行以下操作:

For a real installation script, you'd probably want to be sure that type doesn't return successfully in the case when there is an alias foobar. In bash you could do something like this:

if ! foobar_loc="$(type -p "$foobar_command_name")" || [[ -z $foobar_loc ]]; then
  # install foobar here
fi