Search code examples
bashshellselinux

Bash Script for using grep in an if statement with a for loop


I am trying to make my bash script ssh into each server and then grep Selinux=enforcing/replace with Selinux=permissive. The issue I am facing is it checks the first server and but not the second server. I believe it arises from my if statement.

#!/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 

Solution

  • You can't nest " inside ". If you want to give multiline input to ssh, the easiest way is with a 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