1

When using local variables, the return code ($?) is being reset to 0 instead of the expected 4 (see the printed value of $rc2). Is this intended, or is this a bug in Bash?

I am running Debian:

$ bash --version
GNU bash, version 4.4.12(1)-release (x86_64-pc-linux-gnu)

Example to reproduce:

function foo(){
    echo "Foo text [$1] [$2]"
    return 4
}

echo "Testing function values and return values"
result=$(foo bar 20)
retVal=$?
echo "outside $retVal"
echo "outside $result"

function bar(){
    output1=$(foo bar 20)
    rc1=$?
    local output2=$(foo bar 20)
    rc2=$?
    echo "inside $rc1 and $rc2"
    echo "inside $output1 and $output2"
}

bar

results in the following output:

outside 4
outside Foo text [bar] [20]
inside 4 and 0
inside Foo text [bar] [20] and Foo text [bar] [20]
JeanMarc
  • 306
  • 1
  • 10
  • Shellcheck warns about compound declaration and assignment: https://github.com/koalaman/shellcheck/wiki/SC2155 – Benjamin W. Oct 30 '17 at 13:32
  • Granted that the answer Tom refers to answers the question, I disagree that this qualifies as an exact duplicate. Who would search for 'sweep the return code' when running into this? I certainly did not :) But good to know that separating declaration from assignment solves the issue in this case: local output2 output2=$(foo bar 20) – JeanMarc Oct 30 '17 at 13:39
  • 1
    @JeanMarc Closing a question as a duplicate just means the *answer* to the original answers the current question. Having your question closed as a duplicate isn't supposed to be taken as a slight; it's just an alternative method of answering your question. – chepner Oct 30 '17 at 13:49
  • @chepner, thanks, that clears it up for me (I am a long time reader of SO, but just starting out asking questions and/or trying to answer myself). – JeanMarc Oct 30 '17 at 13:59
  • Also, from now on, if somebody searches with similar terms as you used, they'll find your question, and from there the duplicate. Your question now functions as a signpost. – Benjamin W. Oct 30 '17 at 14:25

0 Answers0