A function that can make caller return
- by icando
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.