简体   繁体   English

命令 grep “$SHELL$” foo

[英]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.我无法理解这个命令的作用,更重要的是命令中 $s 的重要性。 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.我首先创建了一个文件 foo 并用 SHELL、WELL 等字词填充它。然后我尝试了该命令,但它没有打印任何内容,所以我认为我的终端可能有问题。 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. $SHELL扩展为您当前执行的 shell 的路径。 $ without text after it does not expand and stays unaltered. $没有文本后它不会扩展并保持不变。

If executed in the Bash shell, your final command would look like:如果在 Bash shell 中执行,您的最终命令将如下所示:

grep '/bin/bash$' foo

$ as part of a – which is what a grep pattern is – means "end of line". $作为的一部分——这就是grep 模式的含义——表示“行尾”。

You can verify it by prepending your command with echo , or enabling command tracing in your shell: set -x您可以通过在命令前添加echo或在 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:最好明确说明您希望执行 shell 扩展的位置以及不执行的位置:

grep "$SHELL"'$' foo
grep "$SHELL\$" foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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