如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
当前回答
为了模拟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; }
其他回答
我找不到一个可行的解决方案,但编辑了一下后,我想到了这个。这对我有用:
dpkg --get-selections | grep -q linux-headers-$(uname -r)
if [ $? -eq 1 ]; then
apt-get install linux-headers-$(uname -r)
fi
我想回答同样的问题,但要在Makefile中运行。
install:
@if [[ ! -x "$(shell command -v ghead)" ]]; then \
echo 'ghead does not exist. Please install it.'; \
exit -1; \
fi
我在.bashrc中定义了一个函数,这使得这更容易。
command_exists () {
type "$1" &> /dev/null ;
}
下面是一个如何使用它的示例(来自我的.bash_profile)
if command_exists mvim ; then
export VISUAL="mvim --nofork"
fi
哈希变量有一个陷阱:例如,可以在命令行中键入
one_folder/process
以执行进程。为此,one_folder的父文件夹必须位于$PATH中。但当您尝试散列此命令时,它总是会成功:
hash one_folder/process; echo $? # will always output '0'
仅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