Skip to content
Advertisement

If condition met, yet doesn’t run in Bash script

Sorry if a silly question.

I have a script that doesn’t behave how it’s intended even though a condition is met.

My script is something like this:

    state=$(Substate=running)

    systemctl show -p SubState someservice | while read output
    if [ $output = $state ];
    then
    echo "ok"
    else
    echo "not ok"
    fi 

I’ve tried declaring the state variable in different ways but non seem to work;

    state=$(Substate=running)
    state=Substate=running
    state="Substate=running"

also tried [ $output = $state ] [ "$output" = "$state" ] [[ ]] but nothing works.

I think I’m declaring the state variable wrong?

Can anybody point me in the right direction?

Many thanks in advance

Advertisement

Answer

Bash strings compare is case-sensitive, and the output from systemctl sub-state seems to return SubState=running with capital “S” for “State”

And I see you declared your state with lower-case s in “state” –

state=$(Substate=running)
state=Substate=running
state="Substate=running"

So my guess is that your comparing problem relates to case-sensitive string comparison

The following seems to be working for me:

state="SubState=running"
output=$(systemctl show -p SubState someservice)

if [ "$output" == "$state" ]
then
echo "ok"
else
echo "not ok"
fi
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement