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
2010-02-10 13:34:55
That should be `"$x"` unless you're 100% sure that `x` is really set to something.
Aaron Digulla
2010-02-10 13:40:13
@Aaron: I'm not sure I follow -- `$x` is quoted correctly in the example code, yes?
John Feminella
2010-02-10 13:41:22
@John: It wasn't when I posted the comment.
Aaron Digulla
2010-02-11 08:33:08
+1
A:
Or, if you don't need else clause:
[ "$x" == "valid" ] && echo "x has the value 'valid'"
Dev er dev
2010-02-10 13:45:05
+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
2010-02-10 15:49:49
A:
you can also use use case/esac
case "$string" in
"$pattern" ) echo "found";;
esac
ghostdog74
2010-02-10 19:58:35
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
2010-02-11 06:00:23