Lesson 8 / 8
Module 4Lesson 2⏱ 65 min study

Lesson 8: Production Automation: Multi-Directory Backups, System Monitoring & A–Z Command Reference

Engineer an automated, compressed tar backup utility with error auditing, schedule background jobs via cron, inspect real-time system performance, and leverage the administrator's A-Z command reference.

✦ Key Architectural Takeaways
  • •The tar (tape archive) utility combined with gzip compression (tar -czvf) provides standardized, portable filesystem backups.
  • •Production automation scripts implement timestamping, target verification, error checking with exit codes ($?), and automated logging.
  • •Cron manages scheduled recurring background jobs defined by five time fields: minute, hour, day-of-month, month, and day-of-week.
  • •Core administrative monitoring tools include 'top'/'htop' for process hierarchy and CPU load, 'free -m' for RAM/Swap utilization, and 'df -h' for disk space.
  • •The A-Z command reference serves as an essential rapid lookup index for modern Linux administration across filesystems, networking, and security.

1. Engineering a Production-Grade Automated Backup Script

Backing up critical user directories is the quintessential administrative task. Below is a complete, production-hardened Bash script synthesizing file validation, timestamping, tar compression, and exit status logging:

BASHSYSTEM SCHEMATIC
#!/bin/bash
# ==============================================================================
# Script Name : auto_backup.sh
# Purpose     : Automated timestamped compressed backup of critical user data
# ==============================================================================

# Strict error handling: exit immediately if an unhandled command fails
set -euo pipefail

# Configuration Variables
SOURCE_DIR="$HOME/Documents"
BACKUP_DEST="$HOME/backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
ARCHIVE_NAME="backup_documents_${TIMESTAMP}.tar.gz"
LOG_FILE="${BACKUP_DEST}/backup.log"

# Step 1: Ensure destination directory exists
mkdir -p "$BACKUP_DEST"

echo "[$(date)] --- Starting Backup Routine ---" | tee -a "$LOG_FILE"

# Step 2: Verify source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
    echo "[$(date)] ERROR: Source directory '$SOURCE_DIR' does not exist!" | tee -a "$LOG_FILE"
    exit 1
fi

# Step 3: Execute compressed tar archive creation
# -c : create archive | -z : compress with gzip | -v : verbose | -f : output filename
echo "[$(date)] Compressing '$SOURCE_DIR' into '${BACKUP_DEST}/${ARCHIVE_NAME}'..." | tee -a "$LOG_FILE"

tar -czf "${BACKUP_DEST}/${ARCHIVE_NAME}" -C "$HOME" "Documents"

# Step 4: Verify archive integrity and calculate storage size
ARCHIVE_SIZE=$(du -h "${BACKUP_DEST}/${ARCHIVE_NAME}" | cut -f1)
echo "[$(date)] SUCCESS: Backup created successfully (Size: ${ARCHIVE_SIZE})." | tee -a "$LOG_FILE"

# Step 5: Retention Policy: Automatically purge backups older than 14 days
echo "[$(date)] Cleaning archives older than 14 days..." | tee -a "$LOG_FILE"
find "$BACKUP_DEST" -type f -name "backup_documents_*.tar.gz" -mtime +14 -exec rm {} ;

echo "[$(date)] --- Backup Process Completed ---" | tee -a "$LOG_FILE"
§

2. Job Scheduling with Cron

The cron daemon executes tasks automatically in the background on scheduled intervals according to the user's crontab (cron table).

TEXTSYSTEM SCHEMATIC
* * * * * /path/to/command
| | | | |
| | | | +--- Day of the Week (0 - 7, 0 and 7 = Sunday)
| | | +----- Month of Year (1 - 12)
| | +------- Day of Month (1 - 31)
| +--------- Hour (0 - 23)
+----------- Minute (0 - 59)

Common Crontab Schedules

Schedule ExpressionFrequency & Description
0 2 * * *Run every night at 2:00 AM
0 */4 * * *Run every 4 hours at minute 0
30 18 * * 1-5Run Monday through Friday at 6:30 PM
0 0 1 * *Run on the 1st of every month at midnight
@rebootRun once immediately upon operating system startup
BASHSYSTEM SCHEMATIC
# Edit the current user's crontab file in nano
crontab -e

# Example crontab entry: execute the backup script daily at 2:30 AM and log output
30 2 * * * /bin/bash /home/anupam/scripts/auto_backup.sh >> /home/anupam/backups/cron.log 2>&1

# View active scheduled cron tasks
crontab -l
§

3. Real-Time System Monitoring & Resource Sizing

Understanding how to diagnose system performance bottlenecks ensures applications run smoothly:

BASHSYSTEM SCHEMATIC
# 1. Inspect real-time process table, CPU usage, and memory (press 'q' to quit)
top

# 2. Modern colorful interactive process viewer (install via 'sudo apt install htop')
htop

# 3. Display physical RAM and Swap usage in human-readable megabytes
free -h

# 4. Display filesystem disk capacity, mount points, and remaining space
df -h

# 5. Check system uptime, logged in users, and load average over 1, 5, 15 minutes
uptime

# 6. Locate a rogue process by name and terminate it gracefully
pgrep -l python
kill -15 <PID>       # SIGTERM (Graceful shutdown request)
kill -9 <PID>        # SIGKILL (Forceful kernel termination)
§

4. Linux on Embedded Systems: The Raspberry Pi Ecosystem

The guide highlights the synergy between Linux and the Raspberry Pi—the revolutionary single-board computer powered by ARM architecture:

  • Raspberry Pi OS (formerly Raspbian): An optimized Debian derivative tailored specifically for ARM processors with built-in educational and programming tools (Python, Scratch, Thonny).
  • Headless SSH Access: Enabling SSH by creating a blank file named ssh in the boot partition allows remote administration without needing a dedicated monitor, keyboard, or mouse:
BASHSYSTEM SCHEMATIC
  # Remote shell access over local network
  ssh pi@raspberrypi.local
  • Physical Computing (GPIO): 40-pin General Purpose Input/Output header allows direct hardware interaction with sensors, relays, LEDs, and robotic motors via Python libraries (gpiozero, RPi.GPIO).
§

5. Essential A–Z Linux Administrator Command Reference

CommandCategoryFunctional Purpose & Key Flags
adduserUser MgmtInteractively add a new user account with home folder and skeleton files
aliasShell CustomizationCreate a persistent shorthand macro for complex commands (alias ll='ls -la')
aptPackage MgmtAdvanced package tool to search, update, install, and purge packages
catFile I/OConcatenate and display file content to standard output
chmodSecurityChange file mode bits / permissions (chmod 755 script.sh)
chownSecurityChange file owner and group ownership (chown anupam:www-data site.html)
cpFile I/OCopy files and directories recursively (cp -r src/ dest/)
crontabSchedulingSchedule automated background tasks with timing expressions
curlNetworkingTransfer data from or to a server using HTTP, HTTPS, FTP, or SFTP
dfStorageReport filesystem disk space usage across partitions (df -h)
duStorageEstimate file space usage for directories (du -sh /var/log)
findSearchSearch for files in a directory hierarchy by name, type, size, or mtime
freePerformanceDisplay amount of free and used memory and swap space (free -m)
grepText ProcessingPrint lines matching regular expression patterns (grep -rn "TODO" .)
htopPerformanceInteractive, ncurses-based real-time process viewer and system monitor
ipNetworkingShow and manipulate routing, network devices, interfaces, and IP addresses (ip a)
killProcess MgmtSend execution control signals to processes (kill -9 <PID>)
lsFile I/OList directory contents with timestamps, permissions, and sizes
mkdirFile I/OCreate directories (mkdir -p path/to/nested/folder)
mvFile I/OMove or rename files and directories
nanoText EditorUser-friendly command-line text editor with intuitive keyboard shortcuts
pingNetworkingSend ICMP ECHO_REQUEST packets to verify network connectivity
pwdFile I/OPrint full path of the current working directory
rmFile I/ORemove files or directories (rm -rf path/)
rsyncFile I/OFast, versatile, remote and local file-copying and synchronization tool
sudoSecurityExecute a command with elevated superuser privileges
systemctlService MgmtControl the systemd system and service manager (systemctl status ufw)
tarArchivingTape archive utility to create and extract compressed archives (tar -czvf)
topPerformanceDisplay live Linux processes, CPU allocation, and memory load averages
touchFile I/OCreate empty files or update file access and modification timestamps
ufwSecurityUncomplicated Firewall interface for configuring packet filtering rules
unameSystem InfoPrint system information, machine architecture, and kernel release (uname -a)
uptimeSystem InfoTell how long the system has been running and load averages
whoamiUser MgmtPrint the current effective username
zip / unzipArchivingPackage and compress or extract ZIP archives