2

I would like to exit from a script if a function fails. Normally this is not a problem, but it becomes a problem if you use process substituion.

$ cat test.sh
#!/bin/bash

foo(){
  [ "$1" ] && echo pass || exit
}

read < <(foo 123)
read < <(foo)
echo 'SHOULD NOT SEE THIS'

$ ./test.sh
SHOULD NOT SEE THIS

Based on CodeGnome’s answer this seems to work

$ cat test.sh
#!/bin/bash

foo(){
  [ "$1" ] && echo pass || exit
}

read < <(foo 123) || exit
echo 'SHOULD SEE THIS'
read < <(foo) || exit
echo 'SHOULD NOT SEE THIS'

$ ./test.sh
SHOULD SEE THIS
1
  • Hint: your construction of foo doesn't evaluate to what you think it does. As written, your foo function will always return true. You probably wanted foo to contain { test -n "$1" && echo pass; } || exit 1 instead. Commented Jul 24, 2012 at 0:50

1 Answer 1

2

You can use set -e to exit the script on any failure. This is often sufficient on smaller scripts, but lacks granularity.

You can also check the return status of any command or function directly, or inspect the $? variable. For example:

foo () {
  return 1
}

foo || { echo "Return status: $?"; exit 1; }
Sign up to request clarification or add additional context in comments.

2 Comments

Strictly speaking, $? will contain the exit code of read, not foo. If it is important to get foo's exit code, I think you'll just have to avoid process substitution.
Doesn't this only work because read returns non-zero on EOF? I think in the general case, process substitution will not fail the parent command even with errexit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.