如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
当前回答
对于感兴趣的人来说,如果您希望检测已安装的库,则前面的答案中的方法都不起作用。我想你要么要检查路径(可能是头文件之类的),要么就这样(如果你是基于Debian的发行版):
dpkg --status libdb-dev | grep -q not-installed
if [ $? -eq 0 ]; then
apt-get install libdb-dev
fi
从上面可以看到,查询中的“0”表示未安装包。这是“grep”的函数-“0”表示找到匹配项,“1”表示没有找到匹配项。
其他回答
仅zsh,但对于zsh脚本非常有用(例如,在编写完成脚本时):
zsh/parameter模块可以访问内部命令哈希表等。来自man zshmodules:
THE ZSH/PARAMETER MODULE
The zsh/parameter module gives access to some of the internal hash ta‐
bles used by the shell by defining some special parameters.
[...]
commands
This array gives access to the command hash table. The keys are
the names of external commands, the values are the pathnames of
the files that would be executed when the command would be in‐
voked. Setting a key in this array defines a new entry in this
table in the same way as with the hash builtin. Unsetting a key
as in `unset "commands[foo]"' removes the entry for the given
key from the command hash table.
尽管它是一个可加载的模块,但只要zsh不与--simulate一起使用,它似乎是默认加载的。
例子:
martin@martin ~ % echo $commands[zsh]
/usr/bin/zsh
要快速检查某个命令是否可用,只需检查哈希中是否存在密钥:
if (( ${+commands[zsh]} ))
then
echo "zsh is available"
fi
请注意,散列将包含$PATH文件夹中的任何文件,无论它们是否可执行。为了绝对确定,您必须对此进行统计:
if (( ${+commands[zsh]} )) && [[ -x $commands[zsh] ]]
then
echo "zsh is available"
fi
如果你的男人/女孩不能在这里得到答案中的东西,并且你的头发从你的背部,尝试使用bash-c运行相同的命令。看看这个梦游性谵妄。这是运行$(子命令)时真正发生的情况:
第一它可以给你完全不同的输出。
$ command -v ls
alias ls='ls --color=auto'
$ bash -c "command -v ls"
/bin/ls
第二它根本不会给你任何输出。
$ command -v nvm
nvm
$ bash -c "command -v nvm"
$ bash -c "nvm --help"
bash: nvm: command not found
如果您可以:
which programname
...
type -P programname
这里有很多选择,但我很惊讶没有快速的一句话。这是我在脚本开始时使用的方法:
[[ "$(command -v mvn)" ]] || { echo "mvn is not installed" 1>&2 ; exit 1; }
[[ "$(command -v java)" ]] || { echo "java is not installed" 1>&2 ; exit 1; }
这是基于此处选择的答案和另一个来源。
我必须检查Git是否作为部署CI服务器的一部分安装。我最后的Bash脚本如下(Ubuntu服务器):
if ! builtin type -p git &>/dev/null; then
sudo apt-get -y install git-core
fi