shell 用于在带for循环的if语句中使用grep的Bash脚本

roejwanj  于 2022-11-25  发布在  Shell
关注(0)|答案(2)|浏览(218)

我试图把我的bash脚本ssh放到每个服务器上,然后用grep Selinux=enforcing/replace with Selinux=permissive。我面临的问题是它检查第一个服务器,而不是第二个服务器。我相信它是由我的if语句引起的。

#!/bin/bash

selinux_path=/opt/configtest
hosts=(server1 server2)

for my_hosts in "${hosts[@]}"
do
    ssh -q -o "StrictHostKeyChecking no" root@${my_hosts} "
        if [ $(grep -c SELINUX=enforcing $selinux_path) -ne 0 ]
        then 
            echo "------------------------------------------------"
            echo "${my_hosts}"
            echo "------------------------------------------------"
            sed -i 's/SELINUX=enforcing/SELINUX=permissive/g' ${selinux_path}
            echo "Selinux has been changed to permissive"
            cat ${selinux_path}
        else
            echo "------------------------------------------------"
            echo "${my_hosts}"
            echo "------------------------------------------------"
            echo "Selinux has already been changed to permissive"
            cat ${selinux_path}
        fi    
        "
    
done
yv5phkfx

yv5phkfx1#

你不能把"嵌套在"中,如果你想给予ssh多行输入,最简单的方法是使用here-doc。

#!/bin/bash

selinux_path=/opt/configtest
hosts=(server1 server2)

for my_hosts in "${hosts[@]}"
do
    ssh -q -o "StrictHostKeyChecking no" root@${my_hosts} <<EOF
        if grep -q SELINUX=enforcing "$selinux_path"
        then 
            echo "------------------------------------------------"
            echo "${my_hosts}"
            echo "------------------------------------------------"
            sed -i 's/SELINUX=enforcing/SELINUX=permissive/g' ${selinux_path}
            echo "Selinux has been changed to permissive"
            cat "${selinux_path}"
        else
            echo "------------------------------------------------"
            echo "${my_hosts}"
            echo "------------------------------------------------"
            echo "Selinux has already been changed to permissive"
            cat "${selinux_path}"
        fi    
EOF
done
zfycwa2u

zfycwa2u2#

是否尝试为grep、echo、sed和cat指定完整路径?

相关问题