Bash command substitution within a function does not return the return code from the command substitution

32 Views Asked by At

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
0

There are 0 best solutions below