Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh: bash script comparison of dynamically generated string

Tags:

bash

zsh

This works as expected:-

x="None of the specified ports are installed"
if [ "$x" = "None of the specified ports are installed" ]; 
    then echo 1; 
    else echo 0; 
fi

I get 1, which is what I am expecting.

But this does not work:-

y="`port installed abc`"
if [ "$y" = "None of the specified ports are installed" ]; 
    then echo 1; 
    else echo 0; 
fi

I get 0, which is not what I am expecting; even though

echo $y 

gives None of the specified ports are installed.

The main difference here is that $y is dynamically determined by the port installed abc command. But why would that affect my comparison?

like image 853
Calvin Cheng Avatar asked Feb 11 '26 08:02

Calvin Cheng


1 Answers

Notice carefully.

None of the specified ports are installed

not equal

None of the specified ports are installed.
                                         ^
                                        /
                          right there -- 

Another option

y=$(port installed abc)
z='None of the specified ports are installed'
if [[ $y =~ $z ]]
then
  echo 1
else
  echo 0
fi
like image 119
Zombo Avatar answered Feb 15 '26 02:02

Zombo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!