Erik Sapir Erik Sapir - 1 year ago 145
Linux Question

How to compare strings in Bash script

I need to compare a variable to some string (and do something if they match).

Answer Source

Try this:

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

If you want to do something when they don't match, replace == with !=. You want the quotes around $x, because if $x is empty, you'll get if [ == "valid" ]... which is a syntax error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download