如何验证程序是否存在,以返回错误并退出,或继续执行脚本?

看起来应该很容易,但这让我很为难。


当前回答

哈希变量有一个陷阱:例如,可以在命令行中键入

one_folder/process

以执行进程。为此,one_folder的父文件夹必须位于$PATH中。但当您尝试散列此命令时,它总是会成功:

hash one_folder/process; echo $? # will always output '0'

其他回答

hash foo 2>/dev/null:适用于Zshell(Zsh)、Bash、Dash和ash。

type-p foo:它似乎可以使用Z shell、Bash和ash(BusyBox),但不能使用Dash(它将-p解释为一个参数)。

命令-vfoo:适用于Z shell、Bash、Dash,但不适用于ash(BusyBox)(-ash:command:not found)。

还要注意,内置的ash和Dash不可用。

如果没有任何可用的外部类型命令(在这里是理所当然的),我们可以使用符合POSIX的env-i sh-c“type cmd 1>/dev/null 2>&1”:

# Portable version of Bash's type -P cmd (without output on stdout)
typep() {
   command -p env -i PATH="$PATH" sh -c '
      export LC_ALL=C LANG=C
      cmd="$1"
      cmd="`type "$cmd" 2>/dev/null || { echo "error: command $cmd not found; exiting ..." 1>&2; exit 1; }`"
      [ $? != 0 ] && exit 1
      case "$cmd" in
        *\ /*) exit 0;;
            *) printf "%s\n" "error: $cmd" 1>&2; exit 1;;
      esac
   ' _ "$1" || exit 1
}

# Get your standard $PATH value
#PATH="$(command -p getconf PATH)"
typep ls
typep builtin
typep ls-temp

至少在Mac OS X v10.6.8(雪豹)上,使用Bash 4.2.24(2)命令-vls与移动的/bin/ls温度不匹配。

which命令可能有用。男子谁

如果找到可执行文件,则返回0;如果找不到或不可执行,则返回1:

NAME

       which - locate a command

SYNOPSIS

       which [-a] filename ...

DESCRIPTION

       which returns the pathnames of the files which would
       be executed in the current environment, had its
       arguments been given as commands in a strictly
       POSIX-conformant shell. It does this by searching
       the PATH for executable files matching the names
       of the arguments.

OPTIONS

       -a     print all matching pathnames of each argument

EXIT STATUS

       0      if all specified commands are 
              found and executable

       1      if one or more specified commands is nonexistent
              or not executable

       2      if an invalid option is specified

这样做的好处是,它可以确定可执行文件在运行环境中是否可用-这节省了一些问题。。。

对于感兴趣的人来说,如果您希望检测已安装的库,则前面的答案中的方法都不起作用。我想你要么要检查路径(可能是头文件之类的),要么就这样(如果你是基于Debian的发行版):

dpkg --status libdb-dev | grep -q not-installed

if [ $? -eq 0 ]; then
    apt-get install libdb-dev
fi

从上面可以看到,查询中的“0”表示未安装包。这是“grep”的函数-“0”表示找到匹配项,“1”表示没有找到匹配项。

如果为要测试的<Command>设置了POSIX_BUILTINS选项,则命令-v可以正常工作,但如果没有,则可能会失败。(多年来,它一直对我有效,但我最近遇到了一个不起作用的地方。)

我发现以下内容更能防止故障:

test -x "$(which <command>)"

因为它测试三件事:路径、存在和执行权限。