1

I would like a script to exit on a syntax error occurring on a test, but no luck :

bash -n "$0" || exit  # check script syntax

#set -xv
set -o nounset
set -o errexit
set -o pipefail # make pipes fail if one of the piped commands fails

if (( != 0 )); then  # syntax error here
  echo "after if"
fi

echo "should not reach this point, but indeed does"

output is :

./testscript: line 8: ((: != 0 : syntax error: operand expected (error token is "!= 0 ")
should not reach this point, but indeed does

any solution ? thanks

Fanfoue
  • 61
  • 4
  • 1
    The manual clearly explains this. *The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, **part of the test following the if or elif reserved words**, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !.* – oguz ismail Mar 30 '20 at 13:17
  • Does this answer your question? [Automatic exit from bash shell script on error](https://stackoverflow.com/questions/2870992/automatic-exit-from-bash-shell-script-on-error) – Digvijay S Mar 30 '20 at 13:19
  • Yet another reason not to rely on `set -e`. – chepner Mar 30 '20 at 13:36
  • 1
    @oguzismail That manual quote refers to non-zero exit status, though, not syntax errors. – Benjamin W. Mar 30 '20 at 13:37
  • @BenjaminW. The syntax error still manifests as a non-zero exit code for the `((...))` command. – chepner Mar 30 '20 at 13:39
  • The error trap only triggers when your shell is *exiting* due to an error; it's not an exception handler. – chepner Mar 30 '20 at 13:50
  • 1
    From another perspective, a syntax error is not something that should happen at run-time, *period*. It's a bug to fix, not a condition to handle. – chepner Mar 30 '20 at 13:52
  • Adding an error trap handler does not help. – Fanfoue Mar 30 '20 at 14:01
  • There's no good way to do this, but `shellcheck "$0" || exit` would work like a stricter version of your existing `bash -n` check – that other guy Mar 30 '20 at 17:06

0 Answers0