Sunday, 17 April 2016

How to compare a variable to a text string ?


s1="hi"
if [ "hi" == "$s1" ]
then
   echo "match"
fi


INVALID EXAMPLES
1. No spaces between variable/value and brackets OR before/after operator 
if ["hi" == "$s1"]

2. Using -eq operator (used for number comparison)
if [ "hi" -eq "$s1" ]

4. Not using double quotes for string variable
if [ "hi" == $s1 ]

Note: If there is no value or empty string assigned to string variable, it could be read as : 
if [ "hi" == ]

3. Avoid accidental assignment to variable. 
if [ "$s1" == "hi" ]
Note: Always keep value first.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.