Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

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

Writer 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"
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.

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

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy