A Real Automation Script
This lesson pulls everything from the course together into one real script: a log-cleanup tool that takes arguments, validates them, loops over files, and reports what it did.
The goal
A small but genuinely useful script: given a directory and a number of days, delete any .log file in that directory older than that many days, and print a summary of what got removed. It uses arguments, a conditional, a loop, a function, file tests, and proper error handling — everything from the last eleven lessons, in one place.
The full script
bash cleanup-logs.sh
#!/bin/bash set -euo pipefail log() { echo "[$(date +%H:%M:%S)] $1" } # usage: ./cleanup-logs.sh <directory> <days> if [[ $# -ne 2 ]]; then echo "Usage: $0 <directory> <days>" exit 1 fi target_dir="$1" days="$2" if [[ ! -d "$target_dir" ]]; then echo "Error: $target_dir is not a directory" exit 1 fi log "Scanning $target_dir for .log files older than $days days" removed_count=0 for file in "$target_dir"/*.log; do [[ -e "$file" ]] || continue if [[ $(find "$file" -mtime +"$days") ]]; then log "Removing $file" rm "$file" removed_count=$((removed_count + 1)) fi done log "Done. Removed $removed_count file(s)."
$ terminal
./cleanup-logs.sh /var/log/myapp 7
Terminal output
[14:22:01] Scanning /var/log/myapp for .log files older than 7 days [14:22:01] Removing /var/log/myapp/access-old.log [14:22:01] Removing /var/log/myapp/error-old.log [14:22:01] Done. Removed 2 file(s).
Walking through the pieces
set -euo pipefail(lesson 11) turns on strict error handling from the start, so a mistake fails loudly instead of limping on.- The
log()function (lesson 6) centralizes how every status line is formatted, with a timestamp, so the whole script's output stays consistent. $#,$1, and$2(lesson 3) read the directory and day-count arguments, with a usage message if the wrong number was given.- The
-dfile test (lesson 4) confirms the argument is really a directory before doing anything destructive with it. - The
for file in "$target_dir"/*.logloop (lesson 5) walks every matching log file, and[[ -e "$file" ]] || continueskips the case where the glob matched nothing at all. find "$file" -mtime +"$days"checks each file's age, andrmremoves it once confirmed old enough.removed_count(lesson 2) tracks a running total, printed once at the end.
Course complete: that covers the whole Bash course — the shebang and running a script, variables and quoting, reading input and arguments, conditionals with
[[ ]] and file tests, the three loop forms, functions and their exit-code-only "return," arrays, Bash's built-in string expansions, redirecting and reading files, pipes and chaining commands, and exit codes with set -euo pipefail. From here, the natural next step is picking a real, repetitive task on your own machine — a backup, a cleanup job, a deploy step — and automating it the way this lesson just did.