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

Asked

Viewed 4,327 times

3

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

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

how I compare the value of V1 to the string "yes":

2 answers

5


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

if [ "$V1" = "sim" ]; then
....
  • The operator would not be the one of comparison/equality (==) instead of the allocation operator (=) ?

  • @Lacobus when it comes to string is like this.

5

1) Single 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!"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.