How can I do, in a Bash script, to handle the return value of an internal function (which may return a non-zero value) without to be caught by the trap?
For instance, if the perform_test
returns 1 the script is ended because the non-zero return value is trapped and handled by the call of the exit_handler
function.
How can I do to avoid this behaviour?
Thanks
Here the script:
#!/bin/bash
set -o pipefail # trace ERR through pipes
set -o errtrace # trace ERR through 'time command' and other functions
set -o nounset ## set -u : exit the script if you try to use an uninitialised variable
set -o errexit ## set -e : exit the script if any statement returns a non-true return value
exit_handler(){
#...
echo "${error_filename}${error_lineno:+: $error_lineno}: ${error_msg}"
exit "${error_code}"
}
trap exit_handler EXIT # ! ! ! TRAP EXIT ! ! !
trap exit ERR # ! ! ! TRAP ERR ! ! !
perform_test(){
local resultCall=$(...)
if [[ -n ${resultCall} ]]; then
return 0
else
return 1
fi
}
##---------------- MAIN ----------------
perform_test
if [[ $? -eq 0 ]]; then
#...
fi
#...
exit 0
UPDATE:
According to the @choroba's answer (use if perform_test "sthg" ; then
), the return 1 isn't caught by the trap as I expected.
But unfortunately this solution is incomplete for my use case: if the function perform_test
produce an error (ex: command not found, no such file..., etc.), then this error isn't caught by the trap any more & the script doesn't directly stop...
So, how do that "caught error without catching return 1
"?
Here is a working example for illustrating it:
#!/bin/bash
set -o pipefail # trace ERR through pipes
set -o errtrace # trace ERR through 'time command' and other functions
set -o nounset ## set -u : exit the script if you try to use an uninitialised variable
set -o errexit ## set -e : exit the script if any statement returns a non-true return value
exit_handler (){
error_code=$?
if [[ ${error_code} -eq 0 ]]; then
return;
fi
echo "an error has occurred..."
exit "${error_code}"
}
trap exit_handler EXIT # ! ! ! TRAP EXIT ! ! !
trap exit ERR # ! ! ! TRAP ERR ! ! !
perform_test(){
local resultCall=$1
# file.txt doesn't exist
cat file.txt
if [[ -n ${resultCall} ]]; then
echo ">> the variable is non empty"
return 1
else
echo ">> the variable is empty"
return 0
fi
}
##---------------- MAIN ----------------
echo "first test"
if perform_test "sthg" ; then
echo ">test1 has succeed"
else
echo ">test1 has failed"
fi
echo "second test"
perform_test "sthg"
if [[ $? -eq 0 ]] ; then
echo ">test2 has succeed"
else
echo ">test2 has failed"
fi
echo "end"
trap - EXIT ERR
exit 0
Produce the following output:
first test
cat: file.txt: No such file or directory
>> the variable is non empty
>test1 has failed
second test
cat: file.txt: No such file or directory
an error has occurred...