如果安装了某些软件,我如何签入bash脚本?

时间:2013-12-28 14:02:42

标签: bash install package

我想查看软件列表,如果已安装或未安装。如果没有,它应该显示,脚本应该中止/退出。如果我执行一次脚本,输出应如下所示:

  wget is not installed
  telnet is not installed

目前看起来如下:

  wget is not installed

再次执行脚本......

  telnet is not installed

如果未安装当前检查的软件,则当前脚本正在检查已安装的软件并中止/存在。这不好,因为如果每个软件都安装了,你必须运行脚本多次来识别和检查:

  LINUX_DISTRIBUTATION=$(grep -Eo "(Debian|Ubuntu|RedHat|CentOS)" /etc/issue)

  # Debian / Ubuntu
  if [ -f /etc/debian_version ] || [ "$LINUX_DISTRIBUTATION" == "Debian" ] || [ "$LINUX_DISTRIBUTATION" == "Ubuntu" ]; then
          declare -a NEEDED_SOFTWARE_LIST=(bash rsync wget grep telnet sed)

          for SOFTWARE in ${NEEDED_SOFTWARE_LIST[@]}; do
                  dpkg -l | grep -i $SOFTWARE | head -1 | if [[ "$(cut -d ' ' -f 1)" != "ii" ]]; then
                          echo -e "[ ${Red}FAILED ${RCol}]\t$SOFTWARE is NOT installed completely! Please install it...\n";
                          exit 1;
                  fi
          done
  # RedHat / CentOS
  elif [ -f /etc/redhat-release ] || [ "$LINUX_DISTRIBUTATION" == "RedHat" ] || [ "$LINUX_DISTRIBUTATION" == "CentOS" ]; then
          declare -a NEEDED_SOFTWARE_LIST=(bash rsync wget grep telnet sed)

          for SOFTWARE in ${NEEDED_SOFTWARE_LIST[@]}; do
                  if [[ "$(rpm -q $SOFTWARE)" == "package $SOFTWARE is not installed" ]]; then
                          echo -e "[ ${Red}FAILED ${RCol}]\t$SOFTWARE is NOT installed completely! Please install it...\n";
                          exit 1;
                  fi
          done
  else
          echo "[ ${Red}FAILED ${RCol}]\tYour system is currently not supported by this script.";
          exit 1;
  fi

我也认为,我的解决方案不是最好的。任何人都可以调整吗?提前致谢! :)

提示:我两次声明变量“NEEDED_SOFTWARE_LIST”,因为我认为我需要两个软件列表“阵列”,因为某些发行版需要另一个软件包。

1 个答案:

答案 0 :(得分:5)

如果安装了软件包而不是简单地检查某些实用程序的可用性,为什么要执行一次可怕的测试呢?

SCRIPTNAME="${0##*/}"

warn() {
    printf >&2 "$SCRIPTNAME: $*\n"
}

iscmd() {
    command -v >&- "$@"
}

checkdeps() {
    local -i not_found
    for cmd; do
        iscmd "$cmd" || { 
            warn $"$cmd is not found"
            let not_found++
        }
    done
    (( not_found == 0 )) || {
        warn $"Install dependencies listed above to use $SCRIPTNAME"
        exit 1
    }
}

checkdeps wget rsync realpath

但是,如果你想检查Debian上是否安装了软件包,请更换这个噩梦

dpkg -l | grep -i $SOFTWARE | head -1 | if [[ "$(cut -d ' ' -f 1)" != "ii" ]]; then

if dpkg -l $SOFTWARE; then