AI Hints
Home›Linux Tutorial›Loops and Functions
Linux · Lesson 108 of 120

Safer Scripts

Set -e and bash -x.

⏱ 2 min read▶ Video at 2:24:29🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

By default, bash keeps going even after a command fails. That can be dangerous. Imagine a script that fails to change folder, then deletes everything in the wrong place.

Safer Scripts
From the video: Safer Scripts
  • Bash keeps going after errors
  • That can be dangerous
  • Delete in the wrong place?

report.sh

Set dash E, near the top, means stop at the first error. This script makes a reports folder, and copies the notes into it. It works the first time. But what about the second time, when the folder already exists?

nano report.shbash
#!/bin/bash
set -e
echo "Step 1: making the folder"
mkdir reports
echo "Step 2: copying the notes"
cp notes.txt reports/
echo "All done!"

Stopping at the error

First run, all done. Second run, MK dir fails, because reports already exists. Set dash E stops the script right there, so step two never runs. Dollar question mark shows the failure code, one.

Terminal
./report.sh
Step 1: making the folder
Step 2: copying the notes
All done!
./report.sh
Step 1: making the folder
mkdir: cannot create directory ‘reports’: File exists
echo $?
1

Watching with bash -x

When a script misbehaves, run it with bash dash X. It prints every command, with a plus sign, just before running it, with the variables already filled in. You can see exactly where things went wrong.

Terminal
bash -x greet.sh Jo Paris
+ name=Jo
+ echo 'Hi Jo from Paris!'
Hi Jo from Paris!

Summary

Set dash E stops a script at the first error, and bash dash X shows each command as it runs. Next, telling Linux to run your scripts automatically, on a schedule.

Key takeaways
  • set -e
  • echo $?
  • bash -x script.sh
Next up: Scheduling with cron — run scripts automatically