Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare a string to multiple correct values in Bash?

I have the following piece of Bash script:

function get_cms {     echo "input cms name"     read cms     cms=${cms,,}     if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then         get_cms     fi } 

But no matter what I input (correct and incorrect values), it never calls the function again, because I only want to allow 1 of those 3 inputs.

I have tried it with ||, with [ var != value ] or [ var != value1 ] or [ var != value1 ], but nothing works.

Can someone point me in the right direction?

like image 652
eagle00789 Avatar asked Jan 16 '14 09:01

eagle00789


People also ask

How do I compare two string variables in bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

What is the difference between the == and comparison operator when used in bash?

In shell scripting, = and == are for string comparisons and -eq is for numeric ones. So, when comparing the strings, use = or == (depending on which shell you are using, sh or bash ), while to check for equality between integers, use -eq comparison operator.

How do you compare variables to strings?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

How do I compare characters in bash?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.


1 Answers

If the main intent is to check whether the supplied value is not found in a list, maybe you can use the extended regular expression matching built in BASH via the "equal tilde" operator (see also this answer):

if ! [[ "$cms" =~ ^(wordpress|meganto|typo3)$ ]]; then get_cms ; fi 
like image 167
Edgar Grill Avatar answered Oct 15 '22 07:10

Edgar Grill