[5.1+] wait may return wrong status from function with EXIT trap

2022-02-08 Thread Greg Edwards
Configuration Information [Automatically generated, do not change]:
Machine: x86_64
OS: linux-gnu
Compiler: gcc
Compilation CFLAGS: -g -O3 -feliminate-unused-debug-types -pipe -Wall 
-Wp,-D_FORTIFY_SOURCE=2 -fexceptions -Wformat -Wformat-security -m64 
-fasynchronous-unwind-tables -Wp,-D_REENTRANT -ftree-loop-distribute-patterns 
-Wl,-z -Wl,now -Wl,-z -Wl,relro -fno-semantic-interposition -ffat-lto-objects 
-fno-trapping-math -Wl,-sort-common -Wl,--enable-new-dtags -mtune=skylake
uname output: Linux pneuma 5.16.4-1119.native #1 SMP Sat Jan 29 03:03:44 PST 
2022 x86_64 GNU/Linux
Machine Type: x86_64-pc-linux-gnu

Bash Version: 5.1
Patch Level: !PATCHLEVEL!
Release Status: release

Description:

The following simplified reproducer demonstrates an incorrect status being
returned from the test() function when run with bash 5.1 or above.  The correct
status is returned on bash versions 5.0 and below, though it doesn't appear to
run the trap.

---snip---
#!/bin/bash -x

function cleanup() {
echo "do some clean up"
}

function test() {
trap cleanup EXIT
if false; then
echo "do something"
else
return 0
fi
}

test &
wait $!
echo "test() exit status is $?"
---snip---

Example when run on bash 5.1 or above:

$ ./t.sh
+ wait 66914
+ test
+ trap cleanup EXIT
+ false
+ return 0
++ cleanup
++ echo 'do some clean up'
do some clean up
+ echo 'test() exit status is 1'
test() exit status is 1


Some observations about the behavior:

  1) It only occurs if the function has an EXIT trap.  It returns the correct
 status if a RETURN trap is used.

  2) If the function returns with an 'exit 0' instead of a 'return 0', the
 correct status is returned.

  3) If the if/else is rearranged such that the 'return 0' comes from the true 
 case of the if/else, the correct status is returned.

Repeat-By:

See above.



Re: [5.1+] wait may return wrong status from function with EXIT trap

2022-02-08 Thread Chet Ramey

On 2/8/22 12:58 PM, Greg Edwards wrote:


Bash Version: 5.1
Patch Level: !PATCHLEVEL!
Release Status: release

Description:

The following simplified reproducer demonstrates an incorrect status being
returned from the test() function when run with bash 5.1 or above.  The correct
status is returned on bash versions 5.0 and below, though it doesn't appear to
run the trap.


Thanks for the report. It's an easy fix to make sure the correct status is
set before running the exit trap in this case.

Chet

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