views:

114

answers:

4

I need to compare a variable to some string (and do something if they match). How can i do the comparison?

+7  A: 

Try this:

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 want the quotes around $x, because if $x is empty, you'll get if [ == "valid" ]... which is a syntax error.

John Feminella
That should be `"$x"` unless you're 100% sure that `x` is really set to something.
Aaron Digulla
@Aaron: I'm not sure I follow -- `$x` is quoted correctly in the example code, yes?
John Feminella
@John: It wasn't when I posted the comment.
Aaron Digulla
+1  A: 

Or, if you don't need else clause:

[ "$x" == "valid" ] && echo "x has the value 'valid'"
Dev er dev
+1. I like this approach too! I'm not sure I'd recommend it to somebody who's a beginner in bash, though; they might read it later and have to think for a second about what's going on.
John Feminella
A: 

you can also use use case/esac

case "$string" in
 "$pattern" ) echo "found";;
esac
ghostdog74
A: 
if [ "$x" = "valid" ]; then
  echo "x has the value 'valid'"
fi

This is the solution if you are using Kourne Shell (ksh).Observe the single = where as in bash it should be ==

Vijay Sarathi