[ HOME ]    [ RADIO ]    [ COMPUTERS ]    [ FIELD STATION ]    [ ABOUT ]    [ MODERN MODE ]
=== BASH SCRIPTING GUIDE: CONDITIONALS, LOOPS & MENUS ===

Whether you are automating server backups, writing system health checks, or managing local container pipelines, Bash scripting is an essential tool in any administrator’s toolkit. This guide covers core control structures, loops, and how to build a clean, interactive text menu system.


1. Conditional Statements (if, elif, else)

Conditional statements allow your script to make decisions based on file states, string comparisons, or exit codes.

String and Numeric Comparisons

  • Strings: Use = (or ==) for equality and != for inequality.
  • Numbers: Use -eq (equal), -ne (not equal), -gt (greater than), and -lt (less than).

File & Environment Tests

  • -f path checks if a file exists and is a regular file.
  • -d path checks if a directory exists.
  • -z string checks if a string is empty (zero length).

Example Script (check_service.sh)

#!/bin/bash

SERVICE="nginx"

# Check if the service is active using systemctl exit status
if systemctl is-active --quiet "$SERVICE"; then
    echo "[OK] The $SERVICE service is running smoothly."
elif systemctl is-enabled --quiet "$SERVICE"; then
    echo "[WARNING] $SERVICE is disabled, but installed."
else
    echo "[ALERT] $SERVICE is NOT running!"
    # Optional: trigger an automatic restart
    # sudo systemctl start "$SERVICE"
fi

2. Loops (for, while, until)

Loops help you iterate over files, arrays, or run tasks repeatedly until a condition is met.

For Loops (Iterating over lists or files)

#!/bin/bash

# Loop through a static list of backup targets
for dir in "/var/www/" "/etc/nginx" "/var/lib/goaccess"; do
    if [ -d "$dir" ]; then
        echo "Processing target directory: $dir"
    fi
done

While Loops (Reading lines or running counters)

#!/bin/bash

# Simple countdown counter
count=3
while [ $count -gt 0 ]; do
    echo "Starting operation in $count..."
    sleep 1
    ((count--))
done
echo "Executing task now!"

3. Building an Interactive Menu System

Bash has a built-in select construct that makes generating interactive command-line menus remarkably easy. It automatically generates a numbered list, prompts the user for input, and loops until exited.

Example Menu Script (station_menu.sh)

#!/bin/bash

# Ensure script is run in an interactive terminal
PS3="Select an option [1-4]: "

echo "=== W4DXR SYSTEM MAINTENANCE MENU ==="

options=("Check Disk Space" "View Recent Nginx Logs" "Run Site Build Script" "Quit")

select opt in "${options[@]}"
do
    case $opt in
        "Check Disk Space")
            echo "--- Disk Utilization ---"
            df -h /
            echo ""
            ;;
        "View Recent Nginx Logs")
            echo "--- Last 10 Access Log Entries ---"
            tail -n 10 /var/log/nginx/access.log
            echo ""
            ;;
        "Run Site Build Script")
            echo "--- Compiling Hugo Site ---"
            /var/www/build.sh
            echo ""
            ;;
        "Quit")
            echo "Exiting menu. 73!"
            break
            ;;
        *) 
            echo "Invalid option $REPLY. Please choose between 1 and 4."
            ;;
    es
done

Pro-Tips for Robust Scripts

  1. Always use a shebang: Start your scripts with #!/bin/bash.
  2. Quote your variables: Always wrap path or string variables in double quotes (e.g., "$dir" or "$SERVICE") to safely handle spaces and special characters.
  3. Check exit statuses: You can test the success of any prior command instantly using if [ $? -eq 0 ].



W4DXR Retro Terminal | Station Log & Technical Notebook