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

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


当前回答

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

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

其他回答

checkexists() {
    while [ -n "$1" ]; do
        [ -n "$(which "$1")" ] || echo "$1": command not found
        shift
    done
}

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

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

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

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

one_folder/process

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

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

如果您可以:

which programname

...

type -P programname

要像@lhunath建议的那样在Bash脚本中使用哈希:

hash foo &> /dev/null
if [ $? -eq 1 ]; then
    echo >&2 "foo not found."
fi

此脚本运行哈希,然后检查最近命令的退出代码(存储在$?中的值)?,等于1。如果hash没有找到foo,则退出代码将为1。如果存在foo,则退出代码将为0。

&>/dev/null重定向哈希的标准错误和标准输出,以便它不会出现在屏幕上,echo>&2将消息写入标准错误。