[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] difference of $? and ${PIPESTATUS[0]}
From: |
Kerin Millar |
Subject: |
Re: [Help-bash] difference of $? and ${PIPESTATUS[0]} |
Date: |
Mon, 22 Apr 2024 07:44:48 +0100 |
User-agent: |
Cyrus-JMAP/3.11.0-alpha0-379-gabd37849b7-fm-20240408.001-gabd37849 |
On Mon, 22 Apr 2024, at 7:13 AM, felix wrote:
> Hi,
>
> Comming on this very old thread:
>
> On Wed, 4 Dec 2013 14:40:11 -0500, Greg Wooledge wrote:
>>
>> The most obvious difference is that $? is shorter.
>>
>> $? is also POSIX standard (older than POSIX in fact), so it works in sh
>> scripts as well. PIPESTATUS is a Bash extension.
>>
>> Finally, note that if you execute a pipeline, $? will contain the exit
>> status of the last command in the pipeline, not the first command,
>> which is what ${PIPESTATUS[0]} would contain. (If you execute a simple
>> command instead of a pipeline, then they would both have the same value.)
>
> Some asked on StackOverflow.com:
> Why does a Bash while loop result in PIPESTATUS "1" instead of "0"?
> https://stackoverflow.com/q/78351657/1765658
>
> Then after some tests:
>
> if ls /wrong/path | wc | cat - /wrong/path | sed 'w/wrong/path'
> >/dev/null ; then
> echo Don't print this'
> fi ; echo ${?@Q} ${PIPESTATUS[@]@A} $(( $? ${PIPESTATUS[@]/#/+} ))
>
> ls: cannot access '/wrong/path': No such file or directory
> cat: /wrong/path: No such file or directory
> sed: couldn't open file /wrong/path: No such file or directory
> '0' declare -a PIPESTATUS=([0]="2" [1]="0" [2]="1" [3]="4") 7
>
> Where $PIPESTATUS[0]=>2 and $?=>0 !!
>
> I could explain that '$?' is result of bash's if...then...fi group command
> executed correctly and PIPESTATUS hold result of "most-recently-executed
> foreground pipeline", but man page say:
>
> PIPESTATUS
> An array variable (see Arrays below) containing a list of exit
> status values from the processes in the most-recently-executed
> foreground pipeline (which may contain only a single command).
>
> ? Expands to the exit status of the most recently executed fore‐
> ground pipeline.
>
> If so, "$?" have to be equivalent to "${PIPESTATUS[0]}", I think.
No. That would only be true in the event that the pipeline comprises a single
command. The present documentation is correct.
>
> I suggest that man page should be modified to replace "foreground pipeline"
> by "command" under "?" paragraph.
It's worth reading the section of the manual that concerns "Pipelines". Not
least, to concretely understand what they are in grammatical terms, but also to
understand that the exit status of a pipeline is "the exit status of the last
command, unless the pipefail option is enabled". That is, the last command that
constitutes the pipeline; there need not be more than one.
--
Kerin Millar