help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: What does `echo xxx 1>&2xxx` do?


From: Peng Yu
Subject: Re: What does `echo xxx 1>&2xxx` do?
Date: Sat, 8 May 2021 11:22:18 -0500

https://git.savannah.gnu.org/cgit/bash.git/tree/parse.y#n346

How does yylex() know "1" should be treated as a <number> as in "1>&2"
and "1" should be treated as a <word> as in "1 >&2"? Could anybody
explain how this context-dependency is resolved by yylex() in detail?
Thanks.

/* More general tokens. yylex () knows how to make these. */
%token <word> WORD ASSIGNMENT_WORD REDIR_WORD
%token <number> NUMBER


On 5/8/21, Koichi Murase <myoga.murase@gmail.com> wrote:
> 2021年5月8日(土) 21:20 Peng Yu <pengyu.ut@gmail.com>:
>> How the parsing is done?
>
> If we literally interpret the manual, the distinction between
> filenames and file descriptors is not processed at the parsing level.
> The manual says
>
> https://www.gnu.org/software/bash/manual/bash.html#Redirecting-Standard-Output-and-Standard-Error
>> When using the second form, word may not expand to a number or
>> ‘-’. If it does, other redirection operators apply (see
>> Duplicating File Descriptors below) for compatibility reasons.
>
> https://www.gnu.org/software/bash/manual/bash.html#Duplicating-File-Descriptors
>> The operator
>>
>>       [n]>&word
>>
>> is used similarly to duplicate output file descriptors. If n is not
>> specified, the standard output (file descriptor 1) is used. If the
>> digits in word do not specify a file descriptor open for output, a
>> redirection error occurs. If word evaluates to ‘-’, file
>> descriptor n is closed. As a special case, if n is omitted, and word
>> does not expand to one or more digits or ‘-’, the standard output
>> and standard error are redirected as described previously.
>
> So, "1>&2" and "1>&2xxx" are both parsed as "n>& word" and then the
> behavior is switched based on the expanded result of "word".
>
>> The shell grammar seems to be extremely context-sensitive.
>
> Yes.
>
>> So in "1>&2xxx", 2xxx is recognized as a word?
>
> Yes.
>
>> In "1>&2", "2" is also recognized as a word?
>
> Yes.
>
>> "1" is recognized as a word?
>
> No. It is a part of the redirection construct of "n>&"
>
>> What about "1 >&2"? "1" is recognized as a word as well?
>
> Yes. But in that case, "1" is not a part of the redirection but a
> separate argument.
>
>> How does bash knows "1 >&2" and "1>&2" are actually different?
>
> If there is no space, it is treated as a part of the redirection.
>


-- 
Regards,
Peng



reply via email to

[Prev in Thread] Current Thread [Next in Thread]