0

This question is a variation on questions that have been asked before, e.g. How to return an error from a sourced bash script.

What I want, however, is for a sourced function X to call a second function Y, and then return function Y's return code back to the caller.

At the moment, I have got my script working using this pattern:

function_x() {
  function_y || return $?
}

function_y() {
  return 1
}

In practice, however, this leads to lots of return statements all through my code.

Suppose that function Y is in fact a usage function. I then end up with ugly code, that is not very DRY, like this:

_usage() {
  echo "Usage: $0 [-h] OPTIONS"
  return 0
}

function_a() {
  [ "$1" == "-h" ] && _usage && return 1
  some_other_condition && _usage && return 1
  yet_another_condition && _usage && return 1
  ...
}

(My actual code is here.)

Is there a clean way, in general, for a function X to call a second function Y and then return Y's return code back to the caller?

Alex Harvey
  • 14,494
  • 5
  • 61
  • 97

1 Answers1

2

You don't need to do anything: the return status of a Bash function or script is the return status of the last command it executed.

So this:

function_x() {
  # ...
  function_y || return $?
}

Is the same as this:

function_x() {
  # ...
  function_y
}

The return statement doesn't influence the status, so if you want to return the status of a command, just say return after it:

if [ ... ]; do
  function_y
  return
fi

For your last example:

[ "$1" == "-h" ] && _usage && return 1
some_other_condition && _usage && return 1
yet_another_condition && _usage && return 1

You can avoid the duplication this way:

{ [ "$1" == "-h" ] || some_other_condition || yet_another_condition; } && _usage && return 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436