How can I compare a variable to a text string, rather than integer, in an if/else statement?

113,212

Solution 1

Something like this:

act="add"
if [[ $act = "add" ]]
then
    echo good
else
    echo not good
fi

-eq is for number comparison, use = for string comparison

Solution 2

This method would also work. Very similar to @Guru's answer but removes the need for double square brackets.

if [ "$act" == "add" ]
then
echo "Good!"
      else
      echo "Not good!"
fi
Share:
113,212

Related videos on Youtube

tony_perkis666
Author by

tony_perkis666

Updated on September 18, 2022

Comments

  • tony_perkis666
    tony_perkis666 over 1 year

    In the process of writing a shell script, I ran into an issue with the following if/else statement that falls somewhere in the middle of the script:

    if [ $act -eq "add" ]
    then
        read - "add or update: " $comm
        git commit -m "$comm $file"
    else
        git commit -m "$act $file"
    fi
    

    The returning error being:

    ./gitup: line 13: [: add: integer expression expected
    

    and then proceeds with the rest of the script. How can I have the if segment evaluate/compare the variable to a string input rather than an integer; a different error was required when using "!=" among a couple of other things I tried.

  • tony_perkis666
    tony_perkis666 over 11 years
    Thanks. I had tried that, and the script would free, requiring a keystroke, but just found it was caused by an unrelated syntax error further down, so this worked perfectly. Thanks for the help.
  • Daniel Andersson
    Daniel Andersson over 11 years
    @josephmarhee: Note that the [[]] test is a Bash specific construct, and this example works just as well with the POSIX [] as used in the question. If the interpreter is explicitly given as #!/bin/bash or similar, the [[]] can be used without issues (and it is a bit faster than the alternative in Bash, I believe - not that it should be a bottle neck anyway), otherwise one should stick with []. If one doesn't need Bash specifics at all, the script will run a bit faster in e.g. Dash. And POSIX ensures inherent portability.