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.
Bash scripts are a great way to run multiple commands consecutively. When writing a script, we have to remind ourselves that if one command fails, all subsequent commands are still executed. In this article, we'll learn how to prevent this by adding some safeguards.
Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
To set an exit code in a script use exit 0 where 0 is the number you want to return. In the following example a shell script exits with a 1 . This file is saved as exit.sh . Executing this script shows that the exit code is correctly set.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With