I am writing some BASH script and I want it have some error handling mechanism:
function f()
{
command1 || { echo "command1 failed"; return 1; }
command2 || { echo "command2 failed"; return 1; }
command3 || { echo "command3 failed"; return 1; }
command4 || { echo "command4 failed"; return 1; }
}
I want to make this repetitive structure more readable by defining some function:
function print_and_return()
{
echo "$@"
# some way to exit the caller function
}
so that I can write function f as
function f()
{
command1 || print_and_return "command1 failed"
command2 || print_and_return "command2 failed"
command3 || print_and_return "command3 failed"
command4 || print_and_return "command4 failed"
}
What’s the best way to achieve this? Thanks.
Maybe you can use
set -e, though you have to be careful since it exits the shell:As long as the commands diagnose any problems, this function will stop when the first command fails.
Test version:
Output:
NB: When I used the sequence:
Then the function behaved differently under bash 3.2.48 on Mac OS X 10.7.4:
So, inventive, but not wholly reliable.