6

I have a script

#! /bin/sh
set -eux

command_a

command_b | command_c

while [ true ]; do
    command_d
done

I'd like this to fail when any command fails. If command_a fails, the script fails, but if command_b or command_d (not sure about command_c) fail, the script carries on.

3
  • 1
    Add a pipefail option to that also, set -euxo pipefail Commented Dec 13, 2017 at 12:15
  • I'll give it a go. Commented Dec 13, 2017 at 17:16
  • 1
    I'd strongly suggest saying while true; do instead of while [ true ]; do -- the latter implies that while [ false ]; do would behave differently, which it doesn't. Commented Dec 13, 2017 at 20:15

1 Answer 1

5

This should not happen if you are using set -eux, may be I can tell better if I knew the actual command. One way to achieve exiting can be to use ||

while [ true ]; do
    command_d || exit 1
done

a || b means "do a (completely). If it didn't succeed, do b"

Also, you should use set -euxo pipefail

Refer this: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/

Sign up to request clarification or add additional context in comments.

3 Comments

I strongly disagree with the characterization of set -e as "safe". See the exercises in BashFAQ #105 (below the allegory), and the list of incompatibilities between different shells' implementations of set -e at in-ulm.de/~mascheck/various/set-e. Because bash has no way to distinguish between a command correctly returning an exit status that indicates a false result of a test and an exit status indicating an error, set -e's behavior is necessarily full of heuristics that try to guess among the cases.
...among these heuristics is maintaining the "checked" flag to determine whether an operation is considered part of a test or conditional -- its behavior, particular in the context of function calls or compound commands, is almost universally misunderstood.
(set -u is not nearly as bad as set -e, but similarly, it tends to break otherwise correct code not explicitly written for compatibility; consequently, pipefail is the only part of this advice that isn't controversial at all... though even then, its use occasionally leads to surprises).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.