0
0
Bash Scriptingscripting~15 mins

set -e for exit on error in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Using set -e to Exit on Error in Bash Scripts
📖 Scenario: You are writing a simple bash script to run a few commands in order. You want the script to stop immediately if any command fails, so you don't continue with wrong results.
🎯 Goal: Learn how to use set -e in a bash script to make it exit on the first error.
📋 What You'll Learn
Create a bash script with three commands
Add set -e to make the script exit on error
Test the script to see it stops when a command fails
Print a message after the commands to confirm script behavior
💡 Why This Matters
🌍 Real World
In real scripts, <code>set -e</code> helps catch errors early and prevents running commands that depend on previous successful steps.
💼 Career
Many jobs require writing reliable bash scripts for automation. Knowing how to use <code>set -e</code> is essential for safe scripting.
Progress0 / 4 steps
1
Create a bash script with three commands
Create a bash script with these three commands exactly: echo "Start script", ls /nonexistentfolder, and echo "End script".
Bash Scripting
Need a hint?

Use echo to print messages and ls to list a folder that does not exist.

2
Add set -e to exit on error
Add the line set -e at the very top of the script to make it exit immediately if any command fails.
Bash Scripting
Need a hint?

set -e must be the first line in the script.

3
Add a success message after commands
Add a new line at the end of the script that prints echo "Script completed successfully".
Bash Scripting
Need a hint?

This message will only print if no command fails before it.

4
Run the script and observe output
Run the script and observe that it prints Start script, then stops with an error because ls /nonexistentfolder fails. It should NOT print End script or Script completed successfully. Use bash yourscript.sh to run.
Bash Scripting
Need a hint?

The script stops after the error. You will see the error message from ls.