使用 if 条件检测安装程序 iptables 和 firewalld / bash

detecting installer iptables and firewalld with if conditions / bash

正在创建检测脚本

当前系统:

理论上它一定可以工作,但缺少一些东西:

#!/bin/bash
installer_check () {
  if [[ $(apt-get -V >/dev/null 2>&1) -eq 0 ]]; then
    installer=apt
  elif [[ $(yum --version >/dev/null 2>&1) -eq 0 ]]; then
    installer=yum
  fi
}

frw_det_yum () {
  if [[ $(rpm -qa iptables >/dev/null 2>&1) -ne 0 ]]; then
    ipt_status_y=installed_none
  elif [[ $(rpm -qa firewalld >/dev/null 2>&1) -ne 0 ]]; then
    frd_status_y=installed_none
  fi
}

frw_det_apt () {
  if [[ $(dpkg -s iptables >/dev/null 2>&1) -ne 0 ]]; then
    ipt_status_a=installed_none
  elif [[ $(dpkg -s firewalld >/dev/null 2>&1) -ne 0 ]]; then
    frd_status_a=installed_none
  fi
}

echo "checking installer"
installer_check
echo -e "$installer detected"

if [ "$installer" = "yum" ]; then
  echo "runing firewallcheck for yum"
  frw_det_yum
  echo $ipt_status
fi

if  [ "$installer" = "apt" ]; then
  echo "checking installer for apt"
  frw_det_apt
  echo $frd_status_a
fi

我得到的输出:

~# ./script
checking installer
apt detected
checking installer for apt

所以在当前系统中,我没有得到 $frd_status_a

的任何值

如果 firewalld 未安装,您 期望 调用以下正文:

if [[ $(dpkg -s firewalld >/dev/null 2>&1) -ne 0 ]]; then
  frd_status_a=installed_none
fi

但是,让我们看看这实际上做了什么:

  • 将命令 dpkg -s firewalld 的标准输出和标准错误重定向到 /dev/null
  • 捕获该命令的标准输出,并将其与值0
  • 进行数值比较
  • 如果该命令的标准输出(没有标准输出,因为您重定向了它)的数值不是 0,那么我们设置标志。

Of course 永远不会设置该标志,无论 dpkg 命令在调用时执行什么操作,也无论其输出是什么。


改为考虑:

if ! dpkg-query -l firewalld; then
  frd_status_a=installed_none
fi