How can I compare a variable to a text string, rather than integer, in an if/else statement?
Mia Lopez
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"
fiThe returning error being:
./gitup: line 13: [: add: integer expression expectedand 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.
2 Answers
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
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