简体   繁体   中英

the command grep “$SHELL$” foo

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?

$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 – 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM