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

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


当前回答

迟到的回答,但这就是我最后做的。

我只是检查我执行的命令是否返回错误代码。如果返回0,则表示程序已安装。此外,您还可以使用它检查脚本的输出。以这个脚本为例。

foo.sh

#!/bin/bash
echo "hello world"
exit 1 # throw some error code

示例:

# outputs something bad... and exits
bash foo.sh $? -eq 0 || echo "something bad happened. not installed" ; exit 1

# does NOT outputs nothing nor exits because dotnet is installed on my machine
dotnet --version $? -eq 0 || echo "something bad happened. not installed" ; exit 1

基本上,所有这些都是检查命令运行的退出代码。即使命令退出代码不是0,这个问题上最被接受的答案也将返回true。

其他回答

我会尝试调用程序,例如--version或--help,并检查命令是否成功或失败

与set-e一起使用时,如果找不到程序,脚本将退出,您将得到一条有意义的错误消息:

#!/bin/bash
set -e
git --version >> /dev/null

我找不到一个可行的解决方案,但编辑了一下后,我想到了这个。这对我有用:

dpkg --get-selections | grep -q linux-headers-$(uname -r)

if [ $? -eq 1 ]; then
        apt-get install linux-headers-$(uname -r)
fi

如果没有任何可用的外部类型命令(在这里是理所当然的),我们可以使用符合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温度不匹配。

我必须检查Git是否作为部署CI服务器的一部分安装。我最后的Bash脚本如下(Ubuntu服务器):

if ! builtin type -p git &>/dev/null; then
  sudo apt-get -y install git-core
fi

尝试使用:

test -x filename

or

[ -x filename ]

从条件表达式下的Bash手册页:

-x文件如果文件存在且可执行,则为True。