Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a return from a child function cause a return to the parent function?

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

}
like image 363
MOHAMED Avatar asked Dec 14 '22 16:12

MOHAMED


2 Answers

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.

like image 89
Etan Reisner Avatar answered Jan 13 '23 15:01

Etan Reisner


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.

like image 37
anubhava Avatar answered Jan 13 '23 14:01

anubhava