29. Shell Scripting
29.1 Script Structure & The Shebang
Section titled “29.1 Script Structure & The Shebang”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 bashset -euo pipefailThe “Unofficial Bash Strict Mode”
Section titled “The “Unofficial Bash Strict Mode””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 likerm -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:
chmod +x script.sh./script.sh29.2 Variables & Command Substitution
Section titled “29.2 Variables & Command Substitution”Declaring Variables
Section titled “Declaring Variables”No spaces around the = sign:
APP_NAME="nginx"PORT=8080readonly MAX_RETRIES=5 # Constant variableCommand Substitution ($(...))
Section titled “Command Substitution ($(...))”Executes a command and captures its output into a variable:
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) |
Checking Arguments Example
Section titled “Checking Arguments Example”if [ "$#" -lt 2 ]; then echo "Usage: $0 <environment> <version>" exit 1fi29.4 Exit Codes & $?
Section titled “29.4 Exit Codes & $?”Every Linux command produces an exit code between 0 and 255:
0: Success.- Non-zero (1-255): Failure or error.
ping -c 1 8.8.8.8 >/dev/null 2>&1STATUS=$?
if [ $STATUS -eq 0 ]; then echo "Internet reachable"else echo "Network failure! Exit code: ${STATUS}" exit 2fi29.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.
Integer Comparisons
Section titled “Integer Comparisons”-eq(Equal),-ne(Not equal)-gt(Greater than),-ge(Greater or equal)-lt(Less than),-le(Less or equal)
String Comparisons
Section titled “String Comparisons”==(Equal),!=(Not equal)-z "$VAR"(True if variable is empty or unset)-n "$VAR"(True if variable is NOT empty)
File & Directory Tests
Section titled “File & Directory Tests”-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)
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."fi29.6 Loops (for, while)
Section titled “29.6 Loops (for, while)”for Loops
Section titled “for Loops”Iterating over a list or an array:
# Loop over itemsfor SERVER in srv01 srv02 srv03; do echo "Pinging ${SERVER}..." ping -c 1 "${SERVER}" >/dev/null 2>&1 && echo "UP" || echo "DOWN"done
# Loop over filesfor LOG_FILE in /var/log/*.log; do [[ -f "$LOG_FILE" ]] || continue echo "Processing $(basename "$LOG_FILE")..."donewhile Loops
Section titled “while Loops”Reading a file line-by-line:
while IFS= read -r LINE; do echo "User record: ${LINE}"done < "/etc/passwd"29.7 Arrays
Section titled “29.7 Arrays”# Declare an arrayDEPLOY_TARGETS=("web01.internal" "web02.internal" "web03.internal")
# Access elementecho "${DEPLOY_TARGETS[0]}" # web01.internal
# Append itemDEPLOY_TARGETS+=("web04.internal")
# Array lengthecho "Total targets: ${#DEPLOY_TARGETS[@]}"
# Loop through all elementsfor TARGET in "${DEPLOY_TARGETS[@]}"; do echo "Deploying to: ${TARGET}"done29.8 Functions
Section titled “29.8 Functions”Functions keep code modular and readable. Variables defined inside functions should use local to avoid polluting the global scope.
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 functionslog_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 bashset -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 bashset -euo pipefail
THRESHOLD=85ALERT_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}%"fi3. Service Watchdog & Auto-Restart Script
Section titled “3. Service Watchdog & Auto-Restart Script”Monitors critical daemons and restarts them if they fail:
#!/usr/bin/env bashset -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 fidone4. Bulk User Provisioning Script
Section titled “4. Bulk User Provisioning Script”Reads a CSV file (username,group,shell) and provisions accounts with random passwords:
#!/usr/bin/env bashset -euo pipefail
CSV_FILE="${1:-users.csv}"
if [[ ! -f "$CSV_FILE" ]]; then echo "Error: CSV file '$CSV_FILE' not found!" >&2 exit 1fi
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"