
Part 1: Debugging Bash Scripts
Even the best-written Bash scripts can fail due to typos, logic errors, or unexpected inputs. Debugging helps you find and fix problems quickly.
1️⃣ Run Scripts in Debug Mode
Add -x when running a script:
bash -x script.sh
This prints each command before it’s executed.
Add -v to see commands as they’re read:
bash -v script.sh
2️⃣ Add Debug Flags Inside Scripts
Insert this at the top of your script:
#!/bin/bash
set -x # Print commands before execution
To stop debugging in the middle:
set +x # Turn off debug mode
3️⃣ Use echo or printf for Manual Debugging
Strategically place debug messages:
echo “DEBUG: Variable x = $x”
4️⃣ Error Handling with trap
Catch and handle errors:
trap ‘echo “Error on line $LINENO”; exit 1’ ERR
5️⃣ Check Exit Codes
Always test command success:
if ! cp file1.txt /tmp/; then
echo “Copy failed!”
fi
Part 2: The Final Bash Challenge
Time to put everything together. Here’s your ultimate exercise:
Challenge: Automated Backup & Monitoring Script
Requirements:
Create a script auto_backup.sh.
It should:
Check if a directory exists (say, /home/user/documents).
If missing, print an error and exit with code 2.
Create a backup in /home/user/backups with a timestamp.
Log success or failure into backup.log.
If disk usage goes above 80%, print a warning.
- Make it executable and schedule it to run daily at midnight with cron.
This combines variables, conditionals, loops, file operations, redirection, cron, and error handling.
Part 3: The Ultimate Bash Cheatsheet
Here’s a condensed cheatsheet for quick reference:
Navigation & File Management
pwd #Show current directory
ls -al #List all files with details
cd /path #Change directory
mkdir dir #Create directory
touch f.sh #Create file
cp a b #Copy file
mv a b #Move/rename file
rm f.txt #Remove file
File Input/Output
echo “text” > file.txt # Overwrite file
echo “text” >> file.txt # Append to file
cat < file.txt # Read file into stdin
command > out.txt 2>&1 # Redirect stdout+stderr
Variables & User Input
name=“Alice”
echo $name
read -p “Enter age: ” age
echo “You are $age years old.”
Loops & Conditionals
for i in {1..5}; do echo $i; done
if [ -f “file.txt” ]; then
echo “File exists”
else
echo “No file”
fi
Functions
greet() { echo “Hello, $1”; }
greet “World”
Cron Scheduling
crontab -e
0 0 * * * /home/user/auto_backup.sh
Debugging
bash -x script.sh # Debug mode
set -euo pipefail # Strict mode
trap ‘echo “Error on line $LINENO”’ ERR