The best answers to the question “How to compare strings in Bash” in the category Dev.
How do I compare a variable to a string (and do something if they match)?
Or, if you don’t need an else clause:
[ "$x" == "valid" ] && echo "x has the value 'valid'"
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
!=. You can read more about string operations and arithmetic operations in their respective documentation.
Why do we use quotes around
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
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
To compare strings with wildcards, use:
if [[ "$stringA" == *$stringB* ]]; then # Do something here else # Do something here fi
a="abc" b="def" # Equality Comparison if [ "$a" == "$b" ]; then echo "Strings match" else echo "Strings don't match" fi # Lexicographic (greater than, less than) comparison. if [ "$a" \< "$b" ]; then echo "$a is lexicographically smaller then $b" elif [ "$a" \> "$b" ]; then echo "$b is lexicographically smaller than $a" else echo "Strings are equal" fi
- Spaces between
<are redirection operators so escape it with
\<respectively for strings.