Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does \$ reduce to $ inside backquotes [though not inside $(...)]?

Tags:

Going over the POSIX standard, I came across another rather technical/pointless question. It states:

Within the backquoted style of command substitution, <backslash> shall retain its literal meaning, except when followed by: '$' , '`' , or <backslash>.

It's easy to see why '`' and '\' lose their literal meanings: nested command substitution demands a "different" backquote inside the command substitution, which in turn forces '\' to lose its literal meaning. So, for instance, the following different behavior seems reasonable:

$ echo $(echo \\\\)
\\
$ echo `echo \\\\`
\

But what about '$'? I.e., what's the point or, more concretely, a possible benefit of the following difference?

$ echo $(echo \$\$)
$$
$ echo `echo \$\$`
4735

As '$' by itself is not ruled out inside backquotes, it looks like you would use either '$' or '\\\$' all the time, but never the middle case '\$'.

To recap,

$ echo `echo $$` # PID, OK
4735
$ echo `echo \\\$\\\$` # literal "$$", OK
$$
$ echo `echo \$\$` # What's the point?
4735

PS: I know this question is rather technical... I myself go for the more modern $(...) substitution all the time, but I'm still curious.

like image 920
ezequiel-garzon Avatar asked Sep 10 '11 20:09

ezequiel-garzon


1 Answers

By adding a \, you make the inner subshell expand it instead of the outer shell. A good example would be to actually force the starting of a new shell, like this:

$ echo $$
4988
$ echo `sh -c 'echo $$'`
4988
$ echo `sh -c 'echo \$\$'`
4990
$ echo `sh -c 'echo \\\$\\\$'`
$$
like image 160
Jonathan Callen Avatar answered Nov 09 '22 03:11

Jonathan Callen