I want to grep for a variable that has the string test
, but I also want to make sure that it will only find test
if that is the only word on a line.
So, I tried this:
string=test
echo "test" | grep "$string$"
I would like to know if grep
knows that the first part, $string
(in grep "$string$"), is asking to find for the string test
, while the last part, $
(in grep "$string $" is asking to find for test
, but nothing should be after test
in the line. Is grep
able to distinguish $string
as a variable and only $
as the regex for end of the line, or do I have to use a certain way to distinguish them apart?
Grep knows nothing it does not see. If grep sees
$string$
, it will try to match$string{end-of-line}
. What happens is that the shell expands the variable$string
beforegrep
kicks in, so thatgrep
receivestest$
as the regex.But, given the word
$string$
, why is the last$
is not expanded while$string
is? Because$
is not a valid variable name. This is very clear in the POSIX specification:And XBD name states
And there are also special parameters, such as
$$
,$@
,$#
, etc..If you don't want to remember all this, simply follow Gordon Davisson's advice and escape every
$
that should not introduce a variable to ensure it will be preserved.Also remember variables are expanded in double-quotes but not in single quotes.
For that, you need either the regex
^test$
(to anchor the string both to the start and end of line) or to use the-x
flag ofgrep
. Your original attempt would matchAtest
because the regextest$
is not anchored to the start of line.