如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
当前回答
我同意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不符合。
其他回答
这取决于您是否想知道它是否存在于$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/会抑制哪个程序的输出。
尝试使用:
test -x filename
or
[ -x filename ]
从条件表达式下的Bash手册页:
-x文件如果文件存在且可执行,则为True。
迟到的回答,但这就是我最后做的。
我只是检查我执行的命令是否返回错误代码。如果返回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。
我想说,由于悬挂别名,没有任何可移植和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 }
如果你想检查一个程序是否存在,是否真的是一个程序,而不是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