[Toybox] Would someone please explain what bash is doing here?

Chet Ramey chet.ramey at case.edu
Mon Mar 16 06:19:17 PDT 2020


On 3/16/20 8:54 AM, Rob Landley wrote:
> On 3/13/20 1:45 PM, Chet Ramey wrote:
>> On 3/13/20 12:27 PM, enh wrote:
>>
>>>> The dash folks would say so.
>>>
>>> except now you need two shells :-)
>>
>> Well, that's their bed. I would say you only need one, of course.
> 
> Next question: what's the deal with "echo $(<input)"?

It's a special case. If a command in $() parses to a simple command with
exactly one input redirection, it's treated as `cat < input' without the
exec. Bash defers full parsing of the command in parens to the subshell,
but if you recognize it lexically, treating $(< as a single token, you
can skip the fork as well.

> 
> Next question: what does \ mean in backticks?

A couple of things. If it precedes a backquote, it's the standard way to
nest old-style command substitutions:

"Command substitution can be nested. To specify nesting within the
backquoted version, the application shall precede the inner backquotes with
<backslash> characters; for example:

\`command\`
"

Otherwise, it's an escape character but only for a few following
characters:

"Within the backquoted style of command substitution, <backslash> shall
retain its literal meaning, except when followed by: '$', '`', or
<backslash>. The search for the matching backquote shall be satisfied by
the first unquoted non-escaped backquote; during this search, if a non-
escaped backquote is encountered within a shell comment, a here-document,
an embedded command substitution of the $(command) form, or a quoted
string, undefined results occur. A single-quoted or double-quoted string
that begins, but does not end, within the "`...`" sequence produces
undefined results."

The undefined results parts are to accommodate behaviors that differ
between the historical Bourne shell and ksh.

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_03

> 
>   $ echo `X=y; echo $X`
>   y
>   $ echo `X=y; echo \$X`
>   y
>   $ echo `X=y; echo \\$X`
>   $X
>   $ echo `X=y; echo \`$X`
>   bash: command substitution: line 1: unexpected EOF looking for matching ``'
>   bash: command substitution: line 2: syntax error: unexpected end of file
>   $ echo $(X=y; echo \$X)
>   $X
> 
> A single backslash gets eaten, so you need two, which is not how $() works.

Don't use $() for a model of how `` works.

> But
> you can't escape a backtick? 

You can, but you have to escape them in matched pairs for nested command
substitution.


-- 
``The lyf so short, the craft so long to lerne.'' - Chaucer
		 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet at case.edu    http://tiswww.cwru.edu/~chet/



More information about the Toybox mailing list