Reputation: 23
I am having trouble understanding what this command does and more importantly the significance of both the $s in the command. I started by making a file foo and filled it with words like SHELL, WELL, etc. I then tried the command, however it did not print anything, so I thought that maybe something was wrong with my terminal. See my terminal below:
ifsmy12@cloudshell:~/3300/tests/t2 (cs3300-301722)$ cat foo
SHELL
HELL
WELL
SHELL
SWELL
DWELL
FAREWELL
ifsmy12@cloudshell:~/3300/tests/t2 (cs3300-301722)$ grep "$SHELL$" foo
ifsmy12@cloudshell:~/3300/tests/t2 (cs3300-301722)$
I then decided to play around with the command by first trying it without the first $ and then doing the same thing except without the second $. My results are below:
ifsmy12@cloudshell:~/3300/tests/t2 (cs3300-301722)$ grep "$SHELL" foo
ifsmy12@cloudshell:~/3300/tests/t2 (cs3300-301722)$ grep "SHELL$" foo
SHELL
SHELL
I got some results but I am still confused as to what each $ does and why the command does not work with both in place. Can someone explain?
Upvotes: 0
Views: 122
Reputation: 265433
$SHELL
expands to the path of your currently executing shell. $
without text after it does not expand and stays unaltered.
If executed in the Bash shell, your final command would look like:
grep '/bin/bash$' foo
$
as part of a regular-expression – which is what a grep
pattern is – means "end of line".
You can verify it by prepending your command with echo
, or enabling command tracing in your shell: set -x
All that said, using $
unescaped and expecting it to not expand is bad practice (in other words: waiting for surprising stuff to happen). Better to be explicit where you want shell expansion to be performed and where not:
grep "$SHELL"'$' foo
grep "$SHELL\$" foo
Upvotes: 3