如果未安装,则在 for 循环中安装软件包

如果未安装,则在 for 循环中安装软件包

有人可以帮助找出我的 for 循环脚本有什么问题吗?我正在尝试使用 for 循环从变量列表安装包。我的问题是,当获取第一个要安装的包时,同时从列表中获取包。它还会同时安装所有软件包。我如何检查修复它。我需要一次做一个。

REQPKGS="redhat-lsb-core telnet"

for pkg in $REQPKGS; do
    if yum -q list installed "$REQPKGS" > /dev/null 2>&1; then
        echo -e "$pkg is already installed"
    else
        yum install $REQPKGS -y
        echo "Successfully installed $REQPKGS"
    fi
done

我的脚本的结果:

+ REQPKGS='redhat-lsb-core telnet'
+ for pkg in '$REQPKGS'
+ yum -q list installed 'redhat-lsb-core telnet'
+ yum install redhat-lsb-core telnet -y
+ echo 'Successfully installed redhat-lsb-core telnet'
Successfully installed redhat-lsb-core telnet
+ for pkg in '$REQPKGS'
+ yum -q list installed 'redhat-lsb-core telnet'
+ yum install redhat-lsb-core telnet -y
Loaded plugins: product-id, refresh-packagekit, rhnplugin, security, subscription-manager
This system is receiving updates from RHN Classic or RHN Satellite.
Setting up Install Process
Package redhat-lsb-core-4.0-7.el6.x86_64 already installed and latest version
Package 1:telnet-0.17-48.el6.x86_64 already installed and latest version
Nothing to do
+ echo 'Successfully installed redhat-lsb-core telnet'
Successfully installed redhat-lsb-core telnet

答案1

$REQPKGS您在循环中使用数组变量 ( ) 而不是循环变量 ( $pkg),因此它完全按照您的指示执行操作,同时安装两个软件包两次。

将循环内部更改for为:

REQPKGS=(redhat-lsb-core telnet)

for pkg in "${REQPKGS[@]}"; do
    if yum -q list installed "$pkg" > /dev/null 2>&1; then
        echo -e "$pkg is already installed"
    else
        yum install "$pkg" -y && echo "Successfully installed $pkg"
    fi
done

使用for循环时,您定义的变量for保存循环每次迭代的值;在您的情况下,一次包含单个包的变量是$pkg

或者

REQPKGS=(redhat-lsb-core telnet)

yum install -y "${REQPKGS[@]}"

将安装指定的所有未安装的软件包,并跳过所有已安装的软件包。

相关内容