Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't bash flag -e exit when a subshell fails?

Tags:

I'm a bit confused here. My goal here is to have the bash script exit with a non-zero exit code when any of the commands within the script fails. Using the -e flag, I assumed this would be the case, even when using subshells. Below is a simplified example:

#!/bin/bash -e  (false)  echo $? echo "Line reached!" 

Here is the output when ran:

[$]>Tests/Exec/continuous-integration.sh  1 Line reached! 

Bash version: 3.2.25 on CentOS

like image 715
Stefan Ayala Avatar asked Feb 20 '13 01:02

Stefan Ayala


People also ask

Does bash exit if command fails?

With Bash scripting, we have a powerful tool under our belt. 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.

How do you exit a subshell?

Use signals to exit process from subshell This is the mechanism that allows you to exit a command line process by pressing ctrl-c. When you press ctrl-c in your terminal, an interrupt signal (SIGINT) is sent to the current process.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

Does bash need exit?

Often when writing Bash scripts, you will need to terminate the script when a certain condition is met or to take action based on the exit code of a command.


1 Answers

It appears as though this is related to your version of bash. On machines that I have access to, bash version 3.1.17 and 3.2.39 exhibit this behaviour, bash 4.1.5 does not.

Although a bit ugly, a solution that works in both versions could be something like this:

#!/bin/bash -e  (false) || exit $?  echo $? echo "Line reached!" 

There are some notes in the bash source changelog which related to bugs with the set -e option.

like image 151
Austin Phillips Avatar answered Dec 26 '22 12:12

Austin Phillips