A function that can make caller return

Posted by icando on Stack Overflow See other posts from Stack Overflow or by icando
Published on 2012-06-16T03:08:39Z Indexed on 2012/06/16 3:16 UTC
Read the original article Hit count: 100

Filed under:

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.

© Stack Overflow or respective owner

Related posts about bash