如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
当前回答
我使用这个,因为它非常简单:
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内置程序和程序的回声状态进行标准输出,而不使用标准错误。另一方面,如果找不到命令,它只会将状态返回到标准错误。
其他回答
为了模拟Bash的-P cmd类型,我们可以使用POSIX兼容的env-i type cmd 1>/dev/null 2>&1。
man env
# "The option '-i' causes env to completely ignore the environment it inherits."
# In other words, there are no aliases or functions to be looked up by the type command.
ls() { echo 'Hello, world!'; }
ls
type ls
env -i type ls
cmd=ls
cmd=lsx
env -i type $cmd 1>/dev/null 2>&1 || { echo "$cmd not found"; exit 1; }
#!/bin/bash
a=${apt-cache show program}
if [[ $a == 0 ]]
then
echo "the program doesn't exist"
else
echo "the program exists"
fi
#程序不是字面意思,您可以将其更改为要检查的程序名称
对于感兴趣的人来说,如果您希望检测已安装的库,则前面的答案中的方法都不起作用。我想你要么要检查路径(可能是头文件之类的),要么就这样(如果你是基于Debian的发行版):
dpkg --status libdb-dev | grep -q not-installed
if [ $? -eq 0 ]; then
apt-get install libdb-dev
fi
从上面可以看到,查询中的“0”表示未安装包。这是“grep”的函数-“0”表示找到匹配项,“1”表示没有找到匹配项。
哈希变量有一个陷阱:例如,可以在命令行中键入
one_folder/process
以执行进程。为此,one_folder的父文件夹必须位于$PATH中。但当您尝试散列此命令时,它总是会成功:
hash one_folder/process; echo $? # will always output '0'
hash foo 2>/dev/null:适用于Zshell(Zsh)、Bash、Dash和ash。
type-p foo:它似乎可以使用Z shell、Bash和ash(BusyBox),但不能使用Dash(它将-p解释为一个参数)。
命令-vfoo:适用于Z shell、Bash、Dash,但不适用于ash(BusyBox)(-ash:command:not found)。
还要注意,内置的ash和Dash不可用。