Declare and Assign Masks Return Values
some_getter_that_is_not_happy_with_return(){
echo "some-value (BashPID=${BASHPID})"
return 1
}
main() {
echo "main BASHPID: ${BASHPID}"
local return_1=$(some_getter_that_is_not_happy_with_return)
if [[ $? -ne 0 ]]; then
echo "return_1: ${return_1}"
echo.red "unhappy finish"
return 1
fi
echo "return_1: ${return_1}"
echo.green "happy finish"
}
main "${@}"
We would like to get unhappy finish in above scenario, since some_getter_that_is_not_happy_with_return
return 1. However, what we will get is:
main BASHPID: 10039
return_1: some-value (BashPID=10040)
happy finish
Related Shell Check: https://github.com/koalaman/shellcheck/wiki/SC2155
Note if we remove the local the code will work as expected.
With removed local, unhappy finish is reached as we would like
some_getter_that_is_not_happy_with_return(){
echo "some-value (BashPID=${BASHPID})"
return 1
}
main() {
echo "main BASHPID: ${BASHPID}"
return_1=$(some_getter_that_is_not_happy_with_return)
if [[ $? -ne 0 ]]; then
echo "return_1: ${return_1}"
echo.red "unhappy finish"
return 1
fi
echo "return_1: ${return_1}"
echo.green "happy finish"
}
main "${@}"
main BASHPID: 10162
return_1: some-value (BashPID=10163)
unhappy finish