Skip to content

29. Shell Scripting

Every bash script begins with a Shebang (#!) on the very first line. It tells the kernel which interpreter to execute the script with:

#!/usr/bin/env bash
set -euo pipefail

Adding set -euo pipefail at the top of your scripts prevents silent bugs:

  • -e (Exit on error): Immediately exits the script if any command returns a non-zero exit code.
  • -u (Unset variables): Exits with an error if you attempt to use an uninitialized variable (prevents accidental disasters like rm -rf /${UNSET_VAR}).
  • -o pipefail: Prevents errors in a pipeline (cmd1 | cmd2 | cmd3) from being masked if the final command succeeds.

To make a script executable:

Terminal window
chmod +x script.sh
./script.sh

No spaces around the = sign:

Terminal window
APP_NAME="nginx"
PORT=8080
readonly MAX_RETRIES=5 # Constant variable

Executes a command and captures its output into a variable:

Terminal window
CURRENT_DATE=$(date +%Y-%m-%d)
HOSTNAME=$(hostname -s)
FREE_RAM_MB=$(free -m | awk '/Mem:/ {print $4}')
echo "Server ${HOSTNAME} running on ${CURRENT_DATE}. Free RAM: ${FREE_RAM_MB}MB"

29.3 Positional Arguments & Special Variables

Section titled “29.3 Positional Arguments & Special Variables”

When running ./deploy.sh staging v1.2.0:

| Variable | Meaning | Example / Output | |||| | $0 | Name of the script | ./deploy.sh | | $1, $2, $3 | 1st, 2nd, 3rd positional argument | $1 = staging, $2 = v1.2.0 | | $# | Total number of arguments passed | 2 | | $@ | All arguments as separate quoted strings | "staging" "v1.2.0" | | $* | All arguments joined as a single string | "staging v1.2.0" | | $$ | Process ID (PID) of the running script | 14092 | | $? | Exit status code of the last executed command | 0 (Success) or 1-255 (Failure) |

Terminal window
if [ "$#" -lt 2 ]; then
echo "Usage: $0 <environment> <version>"
exit 1
fi

Every Linux command produces an exit code between 0 and 255:

  • 0: Success.
  • Non-zero (1-255): Failure or error.
Terminal window
ping -c 1 8.8.8.8 >/dev/null 2>&1
STATUS=$?
if [ $STATUS -eq 0 ]; then
echo "Internet reachable"
else
echo "Network failure! Exit code: ${STATUS}"
exit 2
fi

29.5 Conditional Statements (if, elif, else)

Section titled “29.5 Conditional Statements (if, elif, else)”

In modern Bash, always prefer [[ ... ]] over [ ... ] because it supports regular expressions, wildcard matching, and does not break on empty variables.

  • -eq (Equal), -ne (Not equal)
  • -gt (Greater than), -ge (Greater or equal)
  • -lt (Less than), -le (Less or equal)
  • == (Equal), != (Not equal)
  • -z "$VAR" (True if variable is empty or unset)
  • -n "$VAR" (True if variable is NOT empty)
  • -f "$FILE" (True if file exists and is a regular file)
  • -d "$DIR" (True if directory exists)
  • -s "$FILE" (True if file exists and is greater than 0 bytes)
  • -x "$FILE" (True if file is executable)
Terminal window
SERVICE="nginx"
if systemctl is-active --quiet "$SERVICE"; then
echo "${SERVICE} is healthy and running."
elif [[ -f "/var/run/${SERVICE}.pid" ]]; then
echo "Warning: PID file exists but service is unresponsive!"
else
echo "${SERVICE} is stopped."
fi

Iterating over a list or an array:

Terminal window
# Loop over items
for SERVER in srv01 srv02 srv03; do
echo "Pinging ${SERVER}..."
ping -c 1 "${SERVER}" >/dev/null 2>&1 && echo "UP" || echo "DOWN"
done
# Loop over files
for LOG_FILE in /var/log/*.log; do
[[ -f "$LOG_FILE" ]] || continue
echo "Processing $(basename "$LOG_FILE")..."
done

Reading a file line-by-line:

Terminal window
while IFS= read -r LINE; do
echo "User record: ${LINE}"
done < "/etc/passwd"
Terminal window
# Declare an array
DEPLOY_TARGETS=("web01.internal" "web02.internal" "web03.internal")
# Access element
echo "${DEPLOY_TARGETS[0]}" # web01.internal
# Append item
DEPLOY_TARGETS+=("web04.internal")
# Array length
echo "Total targets: ${#DEPLOY_TARGETS[@]}"
# Loop through all elements
for TARGET in "${DEPLOY_TARGETS[@]}"; do
echo "Deploying to: ${TARGET}"
done

Functions keep code modular and readable. Variables defined inside functions should use local to avoid polluting the global scope.

Terminal window
log_info() {
local MESSAGE="$1"
local TIMESTAMP
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
echo "[INFO] ${TIMESTAMP} - ${MESSAGE}"
}
log_error() {
local MESSAGE="$1"
local TIMESTAMP
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
echo "[ERROR] ${TIMESTAMP} - ${MESSAGE}" >&2
}
# Calling functions
log_info "Deployment started"
log_error "Failed to bind port 80"

29.9 Production SysAdmin Automation Scripts

Section titled “29.9 Production SysAdmin Automation Scripts”

1. Automated Database & Directory Backup Script

Section titled “1. Automated Database & Directory Backup Script”

A production-ready backup script with compression, timestamping, and automatic rotation (retaining last 7 days):

#!/usr/bin/env bash
set -euo pipefail
BACKUP_DIR="/backups/app"
SOURCE_DIR="/var/www/html"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
ARCHIVE_NAME="backup_${TIMESTAMP}.tar.gz"
RETENTION_DAYS=7
mkdir -p "${BACKUP_DIR}"
echo "Creating compressed backup: ${ARCHIVE_NAME}..."
tar -czf "${BACKUP_DIR}/${ARCHIVE_NAME}" -C "${SOURCE_DIR}" .
echo "Backup created successfully. Size: $(du -sh "${BACKUP_DIR}/${ARCHIVE_NAME}" | cut -f1)"
echo "Pruning backups older than ${RETENTION_DAYS} days..."
find "${BACKUP_DIR}" -type f -name "backup_*.tar.gz" -mtime +"${RETENTION_DAYS}" -delete
echo "Backup routine finished."

2. Disk Space Health Monitor with Alerting

Section titled “2. Disk Space Health Monitor with Alerting”

Checks root / filesystem utilization and fires an alert if usage exceeds 85%:

#!/usr/bin/env bash
set -euo pipefail
THRESHOLD=85
ALERT_EMAIL="sysadmin@example.com"
USAGE=$(df / | awk 'NR==2 {print $5}' | tr -d '%')
if [[ "$USAGE" -gt "$THRESHOLD" ]]; then
MESSAGE="WARNING: Root filesystem utilization is at ${USAGE}% on $(hostname)!"
echo "$MESSAGE"
echo "$MESSAGE" | mail -s "Disk Alert: $(hostname)" "$ALERT_EMAIL"
else
echo "Disk usage healthy: ${USAGE}%"
fi

Monitors critical daemons and restarts them if they fail:

#!/usr/bin/env bash
set -euo pipefail
SERVICES=("nginx" "redis" "postgresql")
for SVC in "${SERVICES[@]}"; do
if ! systemctl is-active --quiet "$SVC"; then
echo "[$(date)] ALERT: ${SVC} is down! Attempting restart..."
systemctl restart "$SVC"
sleep 2
if systemctl is-active --quiet "$SVC"; then
echo "[$(date)] SUCCESS: ${SVC} recovered successfully."
else
echo "[$(date)] CRITICAL: ${SVC} failed to restart!" >&2
fi
fi
done

Reads a CSV file (username,group,shell) and provisions accounts with random passwords:

#!/usr/bin/env bash
set -euo pipefail
CSV_FILE="${1:-users.csv}"
if [[ ! -f "$CSV_FILE" ]]; then
echo "Error: CSV file '$CSV_FILE' not found!" >&2
exit 1
fi
while IFS=',' read -r USERNAME GROUP SHELL; do
# Skip header line or comments
[[ "$USERNAME" =~ ^#.*$ || -z "$USERNAME" ]] && continue
if id "$USERNAME" >/dev/null 2>&1; then
echo "User $USERNAME already exists, skipping."
continue
fi
# Ensure group exists
if ! getent group "$GROUP" >/dev/null; then
groupadd "$GROUP"
fi
# Generate random 16-char password
TEMP_PASS=$(openssl rand -base64 12)
useradd -m -g "$GROUP" -s "$SHELL" "$USERNAME"
echo "${USERNAME}:${TEMP_PASS}" | chpasswd
chage -d 0 "$USERNAME" # Force change on first login
echo "Created user: ${USERNAME} (Temp Password: ${TEMP_PASS})"
done < "$CSV_FILE"