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

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


当前回答

#!/bin/bash
a=${apt-cache show program}
if [[ $a == 0 ]]
then
echo "the program doesn't exist"
else
echo "the program exists"
fi

#程序不是字面意思,您可以将其更改为要检查的程序名称

其他回答

为了模拟Bash的-P cmd类型,我们可以使用POSIX兼容的env-i type cmd 1>/dev/null 2>&1。

man env
# "The option '-i' causes env to completely ignore the environment it inherits."
# In other words, there are no aliases or functions to be looked up by the type command.

ls() { echo 'Hello, world!'; }

ls
type ls
env -i type ls

cmd=ls
cmd=lsx
env -i type $cmd 1>/dev/null 2>&1 || { echo "$cmd not found"; exit 1; }

扩展@lhunath和@GregV的答案,下面是那些希望将该检查轻松放入if语句的人的代码:

exists()
{
  command -v "$1" >/dev/null 2>&1
}

以下是使用方法:

if exists bash; then
  echo 'Bash exists!'
else
  echo 'Your system does not have Bash'
fi

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

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

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

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

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

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

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

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

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