How to compare strings in Bash


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

11/18/2018 7:28:17 AM

Accepted Answer

Using variables in if statements

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

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
10/14/2018 8:48:40 AM

Or, if you don't need else clause:

[ "$x" == "valid" ] && echo "x has the value 'valid'"

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow