在Bash中编写if语句的更好方法

3

我有几个遵循以下模式的脚本,我想知道你们是否有减少行数的建议,或者你们是否更加流畅地完成了这项工作?

我不喜欢的是我使用了太多的$?检查,最终得到了嵌套的if循环 - 不确定这是否是一件坏事。

我希望优化但仍然保持功能的代码如下:

wget -V > /dev/null 2>&1
if [ $? -ne 0 ]; then
    apt install wget
    if [ $? -ne 0 ]; then
        "failed to install wget" 
    fi
fi

你使用的 Linux 发行版是什么? - Gilles Quénot
7行代码没有问题,$?多次使用也没有问题,没有配额限制。 :) 如果您在文件中有相同的模式超过两次,可以编写一个函数,该函数期望名称(“wget”)并多次调用该函数。如果您需要反复使用该功能,则可以将该函数放入.bashrc文件或放入脚本中,然后将其放置在路径中。 - user unknown
4个回答

3

使用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'

再次强调,这是一条简短的命令。

更具体地说,在shell中,hash是一种可靠的方式来检查二进制文件是否存在于$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.

每天学习新东西,之前不知道 #hash :) 谢谢! - user3144292

2

通常情况下,您无需显式检查$?,除非您正在寻找特定的非零退出代码。您可以将代码重写为:

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"

1
谢谢Codeforester!第一个建议仍然需要两个if,但是一行代码听起来很有趣。谢谢! - user3144292

0

我试图理解背后的大局,而我认为你正在尝试重新发明轮子。

所谓的轮子是及其衍生产品上的command-not-found

当命令失败时,它会自动提出建议。

你只需要执行:

 apt-get install command-not-found
 update-command-not-found
 wget -V # or any missing command

0
如果这是一个安装脚本,不要检查,直接安装。任何已经安装的软件包都将被跳过:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接