4

I have a parent function and child function:

parent() {

   child aa1 bb1 cc1
   child aa2 bb2 cc2
   child aa3 bb3 cc3
   child aa4 bb4 cc4

}

child() {
  ....
  if [ some error reason ]; then return 1; fi
  ...
}

How to make the return 1 (of the child) cause a return in the parent and then avoid the execute the remaining child calls?

without adding a check of the returned value after each child call like this

parent() {

   child aa1 bb1 cc1
   e=$?; [ "$e" != "0" ] && return $e
   child aa2 bb2 cc2
   e=$?; [ "$e" != "0" ] && return $e
   child aa3 bb3 cc3
   e=$?; [ "$e" != "0" ] && return $e
   child aa4 bb4 cc4
   e=$?; [ "$e" != "0" ] && return $e

}
MOHAMED
  • 41,599
  • 58
  • 163
  • 268

3 Answers3

6

Add || return to the end of each call. The value returned by return is the return status of the last command executed when not specified. (Thanks kojiro for the reminder).

Or just use set -e if ash supports that (though that has some non-obvious limitations about when it fails to work correctly that make some people suggest that you avoid using it). Run set -e before your commands and any "simple command" failure will cause the shell to exit immediately but the previous solution is more flexible.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
4

Add set -e in your parent function:

parent() {
   set -e
   child aa1 bb1 cc1
   child aa2 bb2 cc2
   child aa3 bb3 cc3
   child aa4 bb4 cc4
}

Then call it as:

( parent )

This will run parent function in a sub-shell and sub-shell will be terminated as soon as there is a non-zero exit status from any of the chile function call.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Etan said in his answer that `the set -e has some non-obvious limitations about when it fails to work correctly that make some people avoid using it`. There is a risk that it doesn't work properly when using set -e? The ash already support set -e – MOHAMED Feb 16 '15 at 14:29
2

There is a solution other than set -e and || return

It's simple, just use exit instead of return and the parent should called in a sub-shell:

parent() {
   child aa1 bb1 cc1
   child aa2 bb2 cc2
   child aa3 bb3 cc3
   child aa4 bb4 cc4
}

child() {
  ....
  if [ some error reason ]; then exit 1; fi
  ...
}

And I call the parent in this way:

( parent )
MOHAMED
  • 41,599
  • 58
  • 163
  • 268