Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to exit when any command (including non-simple commands) fail

Tags:

bash

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.

like image 575
Alexander Collins Avatar asked Dec 13 '17 12:12

Alexander Collins


People also ask

Does a bash script exit when a command fails?

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.

How do you exit a script if command fails?

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.

How do I set an exit code in bash?

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.


1 Answers

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/

like image 122
Ashutosh Bharti Avatar answered Oct 13 '22 10:10

Ashutosh Bharti