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

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


当前回答

这取决于您是否想知道它是否存在于$PATH变量中的某个目录中,或者您是否知道它的绝对位置

if which programname >/dev/null; then
    echo exists
else
    echo does not exist
fi

否则使用

if [ -x /path/to/programname ]; then
    echo exists
else
    echo does not exist
fi

在第一个示例中,重定向到/dev/null/会抑制哪个程序的输出。

其他回答

我同意lhunath不鼓励使用which,他的解决方案对Bash用户完全有效。但是,为了更便于携带,应使用命令-v:

$ command -v foo >/dev/null 2>&1 || { echo "I require foo but it's not installed.  Aborting." >&2; exit 1; }

命令命令符合POSIX。参见此处了解其规范:command-execute一个简单的命令

注意:类型符合POSIX,但类型-P不符合。

扩展@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

我在.bashrc中定义了一个函数,这使得这更容易。

command_exists () {
    type "$1" &> /dev/null ;
}

下面是一个如何使用它的示例(来自我的.bash_profile)

if command_exists mvim ; then
    export VISUAL="mvim --nofork"
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