Bash: handling “[[ statement ]] || echo problem found ; exit 1” logic

bashcontrol flowscripting

In the statement in the title, there is a problem that even if the statement is true, it will still exit with status 1 because, as I understand it:

[[ statement ]] || echo problem found ; exit 1

Evaluates to if the statement is false, echo problem found. Exit with status 1. Even if the statement evaluates true, the exit 1 still happens because it is separate. I thought to fix this by running it in a subshell like so:

[[ statement ]] || (echo problem found ; exit 1)

This seems to do what I want, but is it an acceptable way to handle this?

Best Answer

You must use

[[ statement ]] || { echo problem found ; exit 1; }

The difference is that the brace syntax doesn't create a subshell, which means the exit 1 applies to the current shell. If you use (exit 1) the subshell exits but the current shell continues running.