如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
当前回答
扩展@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
其他回答
这将根据位置判断程序是否存在:
if [ -x /usr/bin/yum ]; then
echo "This is Centos"
fi
如果您可以:
which programname
...
type -P programname
我会尝试调用程序,例如--version或--help,并检查命令是否成功或失败
与set-e一起使用时,如果找不到程序,脚本将退出,您将得到一条有意义的错误消息:
#!/bin/bash
set -e
git --version >> /dev/null
它可能更简单,只是:
#!/usr/bin/env bash
set -x
# if local program 'foo' returns 1 (doesn't exist) then...
if ! type -P foo; then
echo 'crap, no foo'
else
echo 'sweet, we have foo!'
fi
将foo更改为vi以激发其他条件。
我同意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不符合。