Zombo
Zombo

Reputation: 1

Bash exit and process substitution

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

Upvotes: 2

Views: 503

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84363

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; }

Upvotes: 2

Related Questions