Q:

A function that can make caller return

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.

A:

Maybe you can use set -e, though you have to be careful since it exits the shell:
function f()
{
    (
    set -e
    command1
    command2
    command3
    command4
    )
}

As long as the commands diagnose any problems, this function will stop when the first command fails.
Test version:
function f()
{
    (
    set -e
    true
    echo true
    true
    echo true
    false
    echo false
    true
    echo true
    )
}

echo calling function
f
echo still here

Output:
calling function
true
true
still here

NB: When I used the sequence:
echo calling function
if f
then echo still here - f passed
else echo still here - f failed
fi

Then the function behaved differently under bash 3.2.48 on Mac OS X 10.7.4:
calling function
true
true
false
true
still here - f passed

So, inventive, but not wholly reliable.

