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

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


当前回答

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

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

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

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

其他回答

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

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

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

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

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

这将根据位置判断程序是否存在:

    if [ -x /usr/bin/yum ]; then
        echo "This is Centos"
    fi

我使用这个,因为它非常简单:

if [ $(LANG=C type example 2>/dev/null | wc -l) = 1 ]; then 
    echo exists; 
else 
    echo "not exists"; 
fi

or

if [ $(LANG=C type example 2>/dev/null | wc -l) = 1 ]; then
    echo exists
else
    echo "not exists"
fi

它使用shell内置程序和程序的回声状态进行标准输出,而不使用标准错误。另一方面,如果找不到命令,它只会将状态返回到标准错误。

我支持使用“命令-v”。例如:

md=$(command -v mkdirhier) ; alias md=${md:=mkdir}  # bash

emacs="$(command -v emacs) -nw" || emacs=nano
alias e=$emacs
[[ -z $(command -v jed) ]] && alias jed=$emacs