2

I have the following situation. Script A source script B. Script B has a function named check, which does no error handling on any of its executed commands.

check () {
  cmd1
  cmd2
  cmd3
  ...
}

My goal is to call the function check from A, exiting if any of cmd* fails.

I have tried from A "check || exit 1" but if cmd2 fails and cmd3 succeeds, A does not exit. set -e did not do the job for me as well.

Any help is appreciated.

4
  • 1
    set -e seems to work for me. Please, give us more details. Commented Mar 5, 2016 at 20:44
  • 1
    "If a compound command or shell function executes in a context where -e is being ignored, none of the commands executed within the compound command or function body will be affected by the -e setting, even if -e is set and a command returns a failure status." gnu.org/software/bash/manual/html_node/… Commented Mar 5, 2016 at 22:39
  • 2
    you can do cmd1 && cmd2 && cmd3 ... in check, "check || exit 1" should work then. Commented Mar 5, 2016 at 22:56
  • @miken32 : can you point us to where the "context where -e is being ignored" is described/defined? Thanks and Good luck to all. Commented Mar 6, 2016 at 4:51

2 Answers 2

2

You can try a custom exit function.

With fileA :

#!/bin/bash
source fileB
check

and fileB :

#!/bin/bash
declare -a exitcode

check() {
  cmd1
  cmd2
  trap finish EXIT
}

cmd1() { 
  myexit 1
}

cmd2() {
  myexit 0
}

myexit() {
  exitcode+=$1
}

finish() {
  [[ ${exitcode[*]} =~ 1 ]] && exit 1  || exit 0
}

Then :

$ ./fileA; echo $?
1

The exit codes are appended in an array that is checked on exit in the finish() function.

Sign up to request clarification or add additional context in comments.

Comments

2

I figure it out. The problem was that if I "set -e" and call the function "func || exit 1" then func subcommands will continue even if cmd1 fails. Calling simply "func" does the trick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.