Comparison of 2 string variables in shell script Comparison of 2 string variables in shell script shell shell

Comparison of 2 string variables in shell script


No need for an if statement; just use grep:

echo $line | grep "\b$word\b"


You can use if [[ "$line" == *"$word"* ]]

Also you need to use the following to assign variables

line="1234 abc xyz 5678"word="1234"

Working example -- http://ideone.com/drLidd


Watch the white spaces!

When you set a variable to a value, don't put white spaces around the equal sign. Also use quotes when your value has spaced in it:

line="1234 abc xyz 5678"   # Must have quotation marksword=1234                  # Quotation marks are optional

When you use comparisons, you must leave white space around the brackets and the comparison sign:

if [[ $line == *$word* ]]; then    echo $linefi

Note that double square brackets. If you are doing pattern matching, you must use the double square brackets and not the single square brackets. The double square brackets mean you're doing a pattern match operation when you use == or =. If you use single square brackets:

if [ "$line" = *"$word"* ]

You're doing equality. Note that double square brackets don't need quotation marks while single brackets it is required in most situations.