Bash Scripting Masterclass: Automating the Boring Stuff
Variables, loops, functions, and error handling. Writing robust scripts that don't break when you look at them funny.
The shell is your home. Bash functions are your furniture. A good DevOps engineer automates everything that needs to be done more than twice.
The Shebang
Always start with #!/bin/bash. This tells the kernel which interpreter to use.
Strict Mode
Bash is forgiving, which is bad for automation. Add this to the top of every script:
set -euo pipefail
-e: Exit immediately if a command fails (returns non-zero).-u: Treat unset variables as an error (preventsrm -rf /$UNDEFINED_VAR).-o pipefail: If a command in a pipe fails (cmd1 | cmd2), the whole thing fails.
Variables and Expansion
Always quote your variables.
FILE="My File.txt"
rm $FILE # ERROR: Tries to remove "My" and "File.txt"
rm "$FILE" # CORECT: Removes "My File.txt"
Loops: Iterating Files
Don't parse ls. Use globs.
for file in *.jpg; do
echo "Processing $file..."
convert "$file" "${file%.jpg}.png"
done
${file%.jpg} removes the extension. Bash string manipulation is surprisingly powerful.
Functions
Modularity makes scripts readable.
log() {
local level=$1
shift
echo "[$(date +'%Y-%m-%d %H:%M:%S')] [$level] $*"
}
log "INFO" "Backup started"
Trap: Cleaning Up
What if the user hits Ctrl+C? Use trap to run cleanup code.
temp_file=$(mktemp)
trap "rm -f $temp_file" EXIT
echo "Working..." > "$temp_file"
# Even if script errors or exits here, file is deleted.
Bash isn't just for glue code. With discipline, it's a powerful programming language.