What is set -e in bash?
27 October 2023 (Updated 27 October 2023)
You’ll often see this at the start of a bash script:
set -e
This instructs the script to exit if any command it executes exits with a non-zero status code.
For example, in the below script:
#!/bin/bash
set -e
echo "This is a test script."
# This command will fail because the directory does not exist
cd /nonexistent/directory
# This command will not be executed because the script will exit after the cd command fails
echo "You will not see this message."
You’ll see the "This is a test script."
in the console but you won’t see "You will not see this message"
because the cd /nonexistent/directory
command will fail with a non-zero status code. The set -e
causes the script to exit as soon as it encounters a non-zero status code.
If you omit set -e
from the start of the script, you will see the second message.
Tagged:
Bash
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment