0

I find that within a function, using command substitution to put the command output in a variable, using $? to get the exit code from the command substitution returns 0, not the returned code.

The command substitution returns the return code as expected when not in a function.

I would like to access both the text returned and the return code. I know a workaround is to redirect the output to a file and then cat the file to a variable. I would like to avoid using a file.

I have found nothing online to help.

Any thoughts?

bash script demonstrating this:

#!/bin/bash
# 20210511
# return_test.sh
# test of return code within a function

declare -rx this_script=${0##*/}

function return_1 () {
    
    echo "returned text"
    return 1

} # function return_1

function return_test () {
    
    local return_value=$`return_1`
    echo "return 1 \`\`   code = $?"
    echo $return_value
    local return_value=$(return_1)
    echo "return 1 ()   code = $?"
    echo $return_value
    local return_value=$( (return_1) )
    echo "return 1 (()) code = $?"
    echo $return_value
    return_1
    echo "return 1      code = $?"


} # function return_test

echo ""
echo "Starting $this_script"
echo "Test of return codes from a command substituted function called with a function"
echo
return_test
echo
echo "Test not in a function"
return_value=$(return_1)
echo "return 1 ()   code = $?"
echo $return_value
echo
exit

The output:

$ ./return_test.sh

Starting return_test.sh
Test of return codes from a command substituted function called with a function

return 1 ``   code = 0

$returned text

return 1 ()   code = 0

returned text

return 1 (()) code = 0

returned text

returned text

return 1      code = 1

Test not in a function

return 1 ()   code = 1

returned text
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Yes, this is normal and expected behavior. – Charles Duffy May 11 '21 at 18:25
  • Use `local` as a separate command. That is, `local var; var=$(...)` -- the `;` means you don't have this problem. Ideally, just put one line declaring all your locals at the very start of a function. – Charles Duffy May 11 '21 at 18:26
  • BTW, while we're talking best practices for function declaration, don't use the `function` keyword. `return_1() {` needs no `function` -- you're using a hybrid of legacy ksh and POSIX sh syntax that isn't compatible with _either_ legacy ksh (which uses just `function return_1 {` with no `()` or POSIX (which uses `return_1() {` with no `function`). See https://wiki.bash-hackers.org/scripting/obsolete -- there are relevant entries in multiple tables, so don't just stop at the first one. – Charles Duffy May 11 '21 at 18:27
  • Changing to local return value return_value=$`return_1` echo "return 1 \`\` code = $?" and works as desired. Thank you for the quick response. I did not realize local is a command. Good advice in the comments. – Richard Hodgman May 11 '21 at 18:47

0 Answers0