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



我试图使我的bash脚本ssh到每个服务器,然后grep Selinux=强制/替换Selinux=允许。我面临的问题是它检查第一个服务器,但不是第二个服务器。我相信这是由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 

不能在"中嵌套"。如果你想给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 

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

相关内容

  • 没有找到相关文章

最新更新