如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
如何验证程序是否存在,以返回错误并退出,或继续执行脚本?
看起来应该很容易,但这让我很为难。
当前回答
我从来没有得到以前的答案来处理我可以访问的盒子。首先,类型已经安装(做更多的事情)。因此需要内置指令。此命令适用于我:
if [ `builtin type -p vim` ]; then echo "TRUE"; else echo "FALSE"; fi
其他回答
我在.bashrc中定义了一个函数,这使得这更容易。
command_exists () {
type "$1" &> /dev/null ;
}
下面是一个如何使用它的示例(来自我的.bash_profile)
if command_exists mvim ; then
export VISUAL="mvim --nofork"
fi
为了模拟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; }
我必须检查Git是否作为部署CI服务器的一部分安装。我最后的Bash脚本如下(Ubuntu服务器):
if ! builtin type -p git &>/dev/null; then
sudo apt-get -y install git-core
fi
这里有很多选择,但我很惊讶没有快速的一句话。这是我在脚本开始时使用的方法:
[[ "$(command -v mvn)" ]] || { echo "mvn is not installed" 1>&2 ; exit 1; }
[[ "$(command -v java)" ]] || { echo "java is not installed" 1>&2 ; exit 1; }
这是基于此处选择的答案和另一个来源。
这取决于您是否想知道它是否存在于$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/会抑制哪个程序的输出。