How to compare the value of a variable with a string in the shell script

Posted on

Question :

Well, I’m trying to make a comparison like this but bash is interpreting it as a command

if "$V1" = "sim"
then
  ...

How do I compare the value of V1 with the string “yes”:

    

Answer :

The syntax of your if is incorrect, the right one is:

if [ "$V1" = "sim" ]; then
....

    

1) Simple block:

if [ "$V1" == "sim" ]; then
    echo "Sim!"
fi

In a row:

[ "$V1" == "sim" ] && echo "Sim!"

2) Block if/else :

if [ "$V1" == "sim" ]; then
    echo "Sim!"
else
    echo "Nao!"
fi

In a row:

[ "$V1" == "sim" ] && echo "Sim!" || echo "Nao!"

    

Leave a Reply

Your email address will not be published. Required fields are marked *