Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare strings in Bash

Tags:

string

bash

How do I compare a variable to a string (and do something if they match)?

like image 890
Erik Sapir Avatar asked Feb 10 '10 13:02

Erik Sapir


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.

How do you compare in bash?

Here, if we compare String1 and String2 using the = operator at first. As String1 and String2 both have the same length with the same sequence of characters, the comparison operator returns true and hence we get String1 and String2 are equal. as output from the first if-else block of the program.

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.

Can you use == to compare two strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.


1 Answers

Using variables in if statements

if [ "$x" = "valid" ]; then   echo "x has the value 'valid'" fi 

If you want to do something when they don't match, replace = with !=. You can read more about string operations and arithmetic operations in their respective documentation.

Why do we use quotes around $x?

You want the quotes around $x, because if it is empty, your Bash script encounters a syntax error as seen below:

if [ = "valid" ]; then 

Non-standard use of == operator

Note that Bash allows == to be used for equality with [, but this is not standard.

Use either the first case wherein the quotes around $x are optional:

if [[ "$x" == "valid" ]]; then 

or use the second case:

if [ "$x" = "valid" ]; then 
like image 133
John Feminella Avatar answered Sep 29 '22 02:09

John Feminella