bug-bash
[Top][All Lists]
Advanced

[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 08:24:00 +0100
User-agent: Cyrus-JMAP/3.11.0-alpha0-379-gabd37849b7-fm-20240408.001-gabd37849

On Mon, 22 Apr 2024, at 7:44 AM, Kerin Millar wrote:
> 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 just looked at the the Stack Overflow thread. It's not explained by forking, 
at least. Here's a simpler test case, using the true and false builtins.

$ if false; then true; fi
$ echo "$?" "${PIPESTATUS[@]@Q}"
0 '1'

Clearly, ? shows the exit status of if, whereas PIPESTATUS shows the exit 
status of false, which counts as a foreground pipeline in its own right. I 
presume that this is by design but I must agree that it is surprising. I cannot 
find anything in the manual that concretely explains why bash behaves as it 
does in this instance.

Here is another case in which the pipeline comprises two compound commands, 
with the values of $? and PIPESTATUS being exactly as one would expect.

$ if false; then true; fi | if true; then false; fi; echo "$?" 
"${PIPESTATUS[@]@Q}"
1 '0' '1'

-- 
Kerin Millar



reply via email to

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