How do I use a variable in the grep search string?
foo="he"
echo 'hello' | grep $foo
returns what I expect (namely hello
).
However
echo 'hello' | grep '^$foo'
returns empty. I guess the variable is not placed in the string, but how do I get it to work?
>Solution :
Use double-quotes, otherwise you are looking for the literal string $foo
not the variable contents. It is also a good idea to escape the variable for clarity:
echo 'hello' | grep "^${foo}"