Practical Scripts
Concepts
This lesson brings together everything from the shell scripting module. No new concepts — just real-world application. Each script below is a practical tool you might actually use. Study them, run them, and modify them.
Lab
Script 1: Backup Script
A script that creates timestamped compressed backups of a directory.
cd ~/lab/scripts
cat > backup.sh << 'SCRIPT'
#!/bin/bash
set -euo pipefail
# --- Configuration ---
BACKUP_DIR="${HOME}/backups"
# --- Functions ---
die() { echo "ERROR: $1" >&2; exit 1; }
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"; }
usage() {
echo "Usage: $0 <source_directory>"
echo "Creates a timestamped backup in $BACKUP_DIR"
exit 1
}
# --- Validate ---
[[ $# -eq 1 ]] || usage
SOURCE="$1"
[[ -d "$SOURCE" ]] || die "Source directory does not exist: $SOURCE"
# --- Prepare ---
mkdir -p "$BACKUP_DIR"
BASENAME=$(basename "$SOURCE")
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/${BASENAME}_${TIMESTAMP}.tar.gz"
# --- Execute ---
log "Starting backup of '$SOURCE'"
log "Destination: $BACKUP_FILE"
tar -czf "$BACKUP_FILE" -C "$(dirname "$SOURCE")" "$BASENAME"
SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
log "Backup complete: $BACKUP_FILE ($SIZE)"
# --- Show recent backups ---
echo ""
echo "Recent backups:"
ls -lht "$BACKUP_DIR"/${BASENAME}_*.tar.gz 2>/dev/null | head -5
SCRIPT
chmod +x backup.sh
# Test it
mkdir -p ~/lab/testdata
echo "important file" > ~/lab/testdata/data.txt
echo "config" > ~/lab/testdata/settings.conf
./backup.sh ~/lab/testdata
ls -lh ~/backups/
Script 2: Log Analyzer
A script that parses a log file and reports statistics.