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

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


当前回答

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

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

其他回答

尝试使用:

test -x filename

or

[ -x filename ]

从条件表达式下的Bash手册页:

-x文件如果文件存在且可执行,则为True。

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

one_folder/process

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

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

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

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

假设您已经遵循了安全壳做法:

set -eu -o pipefail
shopt -s failglob

./dummy --version 2>&1 >/dev/null

这假设命令可以以这样的方式调用,即它(几乎)什么都不做,比如报告其版本或显示帮助。

如果找不到伪命令,Bash将退出并返回以下错误。。。

./my-script: line 8: dummy: command not found

这比其他命令-v(和类似的)回答更有用,也更不冗长,因为错误消息是自动生成的,并且还包含相关的行号。

如果你想检查一个程序是否存在,是否真的是一个程序,而不是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