Bjoern
Bjoern

Reputation: 41

How to keep a bash script running when "set +e" is not enough?

I am calling a command written in C++ from a bash script (on Ubuntu 10.10). The command throws an exception and terminates, and the script is aborted.

Even with "set +e" or "command || true", the script will not continue.

How can I force the script to continue?

Upvotes: 4

Views: 4881

Answers (1)

aks
aks

Reputation: 2348

The shell script can trap any signal except 9 (KILL), with the "trap" command. The special signal name "ERR" means any non-zero error status.

trap 'error=1' ERR
while true; do
  run-external-program
  code="$?"
  if [[ -n "$error" ]]; then
    echo "Caught an error! Status = $code"
    error=  # reset the error
  elif [[ "$code" != 0 ]]; then
    echo "Program exited with non-zero code: $code"
  fi
done

You can also tell the shell to ignore errors with an empty command:

   trap '' ERR

Upvotes: 4

Related Questions