[英]A better way to write an if statement in Bash
有几个脚本遵循以下模式,我很好奇,如果你们有减少行数的建议,或者你是否这样做更精简?
我不喜欢的是我使用了太多$? 检查,并最终得到嵌套的if循环 - 不确定这是否是一件坏事。
代码我正在寻求优化,但仍然保持功能是这样的:
wget -V > /dev/null 2>&1
if [ $? -ne 0 ]; then
apt install wget
if [ $? -ne 0 ]; then
"failed to install wget"
fi
fi
oneliner使用hash
:
hash wget 2>/dev/null || echo 'wget is not installed'
如果您需要安装,您可以这样做
hash wget 2>/dev/null || apt install -y wget || echo 'failed to install wget'
再次,oneliner。
更具体地说, hash
是shell中检查$PATH
是否存在二进制文件的可靠方法。 您可以查看有关hash
信息,如下所示:
$ help hash
hash: hash [-lr] [-p pathname] [-dt] [name ...]
Remember or display program locations.
Determine and remember the full pathname of each command NAME. If
no arguments are given, information about remembered commands is displayed.
Options: ...
Exit Status:
Returns success unless NAME is not found or an invalid option is given.
一般来说,你不需要检查$?
明确除非您正在寻找特定的非零退出代码。 您可以将代码重写为:
if ! wget -V &> /dev/null; then
if ! apt install wget; then
echo "failed to install wget"
fi
fi
或者,更简洁:
wget -V &> /dev/null || apt install wget || echo "failed to install wget"
我试图把大局放在后面,我认为你试图重新发明轮子。
这个轮子在debian和衍生品上command-not-found
。
它在命令自动失败时提出建议。
你只需要这样做:
apt-get install command-not-found
update-command-not-found
wget -V # or any missing command
如果这是安装程序脚本,请不要检查,只需安装。 无论如何都将跳过已安装的任何软件包:
apt install wget jq texlive-latex-base || exit 1
如果这是一个普通的脚本, 请不要安装缺少的依赖项 ,尤其是在未经用户同意的情况下。 这不是脚本的工作,而且它更具侵入性而不是有用。
如果你还想这样做,那就把它放在一个函数中。 这是一个例子:
require() {
# Assume $1 is command and $3 is package (or same as command)
set -- "$1" from "${3:-$1}"
if ! { type "$1" > /dev/null 2>&1 || apt install "$3"; }
then
echo "$1 was missing, but installation of $3 failed" >&2
exit 1
fi
}
require wget
require jq
require latex from texlive-latex-base
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.