Exit Shell script with error if any command fails
I wrote a Bash script today to automate my code review process and I noticed that even when certain commands in the workflow fail, the script still executes the remaining commands.
For example, let's say I have two commands that run synchronously:
git merge origin/dev
git tag <new-tag>
In this case, if the `git merge` command fails due to some reason, it will still create a new tag, which is not my intended workflow.
To avoid this, if any of the commands returns a non-zero exit status, the script should break and exit. This can be achieved in Bash by using the `-e` option.
Add the following at the very top of your script (below the shebang line):
#!/bin/bash
set -e
This will enable the `-e` option for the entire script.
If you only want to enable this option for specific commands, you can prefix them with `set -e`, like this:
set -e
git push
This will cause the script to exit if the `git push` command fails.