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
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.
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.
$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.
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.
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.
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