First, whenever you're using the value of a variable, you need to write $line
.
Also, note that read line
strips off leading and trailing whitespace, and allows the sequence backslash-newline as a line continuation. To retain whitespace, use IFS= read
. To avoid treating \
specially, use read -r
. You can of course combine the two as IFS= read -r
.
What do you want to test exactly? If you want to test that the line is exactly $key
(except for whitespace unless you use IFS= read
), use the ==
operator, and make sure to put $key
in double quotes.
if [[ $line == "$key" ]]; then …
If you want to test that the line contains $key
(so for example if the value of key
is fu*bar
then hellofu*bar
and fu*barqux
match, but fuubar
and gu*bar
don't), then use the ==
operator and again make sure to put $key
in double quotes. The right-hand side of the ==
operator is a shell wildcard pattern; putting the variable in double quotes causes it to be treated literally.
if [[ $line == *"$key"* ]]; then …
If you want to treat $key
as a wildcard pattern, so that if $key
is fu*bar
then the line can be fubar
or fuqwebar
but not fbar
or afubar
, then leave off the double quotes:
if [[ $line == $key ]]; then …
If you only want part of the line to match, allowing things like afubar
:
if [[ $line == *$key* ]]; then …
Use the regular expression match operator =~
if you want to have an extended regular expression on the right-hand side. A regular expression can match part of the line; if you want to match the whole line, put ^
at the beginning of the regex and $
at the end. For example, [[ $line == *"$key"* ]]
is equivalent to [[ $line =~ "$key" ]]
while [[ $line == "$key" ]]
is equivalent to [[ $line =~ ^"$key"$ ]]
.
*$key*
would be quite the odd pattern to match if$key
were something like^foo
orfoo$
, resulting in a pattern of*^foo*
or*foo$*
.