5

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?

3 Answers 3

7

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.

3

You need to use syntax like this :

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

and more accurate send standard error

[[ statement ]] || { echo >&2 "problem found"; exit 1; }
1
  • 1
    Thanks! More notes for beginners: 1) You must leave one whitespace after both the opening and closing brace. 2) Don't forget the semicolon after the last statement! If you do, you will get a very pointless (and misleading) error message: ''unexpected end of file'' (?!?) Feb 12, 2015 at 19:51
3

Don't try to be clever. Remember that debugging is twice as hard as writing, so when you're writing a program, be only half as clever as you can be.

if ! [[ statement ]]; then
  echo problem found
  exit 1
fi
1
  • +1 For the quote. I don't know why one-liners are so popular on SE and in general, as most of them are buggy and hard to understand/read.
    – user13742
    Dec 10, 2013 at 23:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.