Home > OS >  Bash Scripts IF Statements using a command with grep
Bash Scripts IF Statements using a command with grep

Time:12-02

I am having issues with this if statement. Where I want it to grep rpm packages and if they exist and have the exact version specified then return "package installed with correct version" but if they do not then "package installed with incorrect version".

#!/bin/bash
server_host=(server1 server2)


for my_hosts in "${server_host[@]}"
do
    ssh -q -o "StrictHostKeyChecking no" root@${my_hosts} <<EOF
        if [ ! $(rpm -qa | grep "service-7.0.0-1.x86_64") ]
        then
            echo "------------------------------------------------"
            echo "${my_hosts}"
            echo "------------------------------------------------"
            echo "package installed with incorrect version"
        else
            echo "------------------------------------------------"
            echo "${my_hosts}"
            echo "------------------------------------------------"
            echo "package installed with correct version"
        fi

EOF
done

CodePudding user response:

There is no need to enclose the test in [ ... ], nor run it in a sub-shell. Also, no need to test for a negative return, just invert the then ... else ... clauses. Try this:

if rpm -qa | grep "service-7.0.0-1.x86_64"
    then
        echo "------------------------------------------------"
        echo "${my_hosts}"
        echo "------------------------------------------------"
        echo "package installed with correct version"
    else
        echo "------------------------------------------------"
        echo "${my_hosts}"
        echo "------------------------------------------------"
        echo "package installed with incorrect version"
    fi

And, to optimize further:

if rpm -qa | grep "service-7.0.0-1.x86_64"; then
    result="correct"
else
    result="incorrect"
fi
echo "------------------------------------------------"
echo "${my_hosts}"
echo "------------------------------------------------"
echo "package installed with ${result} version"

Or, even further:

rpm -qa | grep "service-7.0.0-1.x86_64" && result="correct" || result="incorrect"
echo "------------------------------------------------"
echo "${my_hosts}"
echo "------------------------------------------------"
echo "package installed with ${result} version"
  • Related