On 7/27/23 4:31 AM, Denys Vlasenko wrote:
Try these two commands:

$ echo "Date: `date #comment`"
Date: Thu Jul 27 10:28:13 CEST 2023

$ echo "Date: $(date #comment)"
)"
Date: Thu Jul 27 10:27:58 CEST 2023


As you see, #comment is handled differently in `` and $().

Yes. There's a hint in the POSIX spec as to why.

POSIX says you can parse `` command substitution lexically, by scanning for
the ending ` by skipping over other constructs and appropriately backslash-
quoting nested command substitutions. It's possible to do this because the
backquote doesn't have any other semantic meaning to the parser. Of course,
everything else the lexer may encounter while finding the closing backquote
is unspecified and implementation defined.

The $(...) form, on the other hand, is required to accept "any valid shell
script," and since the parens have other semantic meaning (and may not need
to be balanced), as a practical matter this means you need to recursively
invoke the parser in order to locate the closing right paren. So what you
do is read the "$(", run the parser recursively to parse a command, and
make sure the next token you read is a ")".

You can see where this goes. Once you commit to running the parser to find
the closing right paren, all normal lexing rules apply. Comments discard
characters until a newline.

Everyone does it this way, including pre-bash-5.2, which used ad-hoc
parsing to locate the closing right paren.

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


Reply via email to