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

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


当前回答

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

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

其他回答

剧本

#!/bin/bash

# Commands found in the hash table are checked for existence before being
# executed and non-existence forces a normal PATH search.
shopt -s checkhash

function exists() {
 local mycomm=$1; shift || return 1

 hash $mycomm 2>/dev/null || \
 printf "\xe2\x9c\x98 [ABRT]: $mycomm: command does not exist\n"; return 1;
}
readonly -f exists

exists notacmd
exists bash
hash
bash -c 'printf "Fin.\n"'

后果

✘ [ABRT]: notacmd: command does not exist
hits    command
   0    /usr/bin/bash
Fin.

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

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

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

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

如果你想检查一个程序是否存在,是否真的是一个程序,而不是Bash内置命令,那么命令、类型和散列不适合测试,因为它们都会返回内置命令的0退出状态。

例如,时间程序提供了比时间内置命令更多的功能。要检查程序是否存在,我建议使用以下示例中的哪个:

# First check if the time program exists
timeProg=`which time`
if [ "$timeProg" = "" ]
then
  echo "The time program does not exist on this system."
  exit 1
fi

# Invoke the time program
$timeProg --quiet -o result.txt -f "%S %U + p" du -sk ~
echo "Total CPU time: `dc -f result.txt` seconds"
rm result.txt

我同意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不符合。