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

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


当前回答

我想回答同样的问题,但要在Makefile中运行。

install:
    @if [[ ! -x "$(shell command -v ghead)" ]]; then \
        echo 'ghead does not exist. Please install it.'; \
        exit -1; \
    fi

其他回答

如果您可以:

which programname

...

type -P programname

我想说,由于悬挂别名,没有任何可移植和100%可靠的方法。例如:

alias john='ls --color'
alias paul='george -F'
alias george='ls -h'
alias ringo=/

当然,只有最后一个是有问题的(林戈没有冒犯!)。但从command-v的角度来看,它们都是有效的别名。

为了拒绝像ringo这样的悬空命令,我们必须解析shell内置别名命令的输出并递归到它们中(这里命令-v并不优于别名)。没有任何可移植的解决方案,即使是特定于Bash的解决方案也相当乏味。

注意,类似这样的解决方案将无条件拒绝别名ls='ls-F':

test() { command -v $1 | grep -qv alias }

迟到的回答,但这就是我最后做的。

我只是检查我执行的命令是否返回错误代码。如果返回0,则表示程序已安装。此外,您还可以使用它检查脚本的输出。以这个脚本为例。

foo.sh

#!/bin/bash
echo "hello world"
exit 1 # throw some error code

示例:

# outputs something bad... and exits
bash foo.sh $? -eq 0 || echo "something bad happened. not installed" ; exit 1

# does NOT outputs nothing nor exits because dotnet is installed on my machine
dotnet --version $? -eq 0 || echo "something bad happened. not installed" ; exit 1

基本上,所有这些都是检查命令运行的退出代码。即使命令退出代码不是0,这个问题上最被接受的答案也将返回true。

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

要像@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将消息写入标准错误。