0
0
Bash Scriptingscripting~5 mins

set -e for exit on error in Bash Scripting

Choose your learning style9 modes available
Introduction

The set -e command makes your script stop running as soon as any command fails. This helps catch mistakes early and avoid unexpected results.

When you want your script to stop immediately if a command has an error.
When running a series of commands where each depends on the previous one succeeding.
When automating tasks and you want to avoid continuing after a failure.
When debugging scripts to find where errors happen quickly.
Syntax
Bash Scripting
set -e

This command is usually placed near the top of your script.

It affects all commands after it in the script.

Examples
This script stops if mkdir, cd, or rm fails.
Bash Scripting
#!/bin/bash
set -e

mkdir new_folder
cd new_folder
rm some_file.txt
If cp fails, the script stops and ls does not run.
Bash Scripting
#!/bin/bash
set -e

cp file1.txt file2.txt
ls file2.txt
Sample Program

This script uses set -e. The command false always fails, so the script stops before printing the last line.

Bash Scripting
#!/bin/bash
set -e

echo "Start script"

false

echo "This line will not run"
OutputSuccess
Important Notes

Not all commands failing will stop the script if they are part of conditions or handled carefully.

You can disable set -e temporarily with set +e if needed.

Summary

set -e stops the script on any error.

Use it to catch problems early and avoid running bad commands.

Place it near the start of your script for best effect.