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
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With