Shell Script Examples
This page provides a collection of practical shell scripts frequently used in DevOps for automation, system maintenance, and task orchestration.
1. The Foundation: Basic Script
Every shell script should start with a shebang and clear, documented logic.
#!/bin/bash
# Description: My first shell script
echo "--- Script Started ---"
echo "Initializing environment..."
echo "Hello, world! Scripting is powerful."2. Using Variables
Variables make your scripts dynamic and reusable.
#!/bin/bash
# Define variables
NAME="John Doe"
ROLE="DevOps Engineer"
SERVER="Web-Server-01"
# Access variables
echo "User: $NAME"
echo "Role: $ROLE"
echo "Connected to: $SERVER"3. Gathering System Information
Scripts are commonly used to pull health metrics from a server.
#!/bin/bash
echo "--- System Health Report ---"
echo "Current Date: $(date)"
echo "Host Information: $(whoami) @ $(hostname)"
echo "System Uptime: $(uptime -p)"
echo "Memory Usage:"
free -h | grep "Mem"4. Interactive Scripts: User Input
Prompting for input makes tools more user-friendly.
#!/bin/bash
echo "What is your project name?"
read PROJECT
echo "Enter target environment (prod/stage):"
read ENV
echo "Setting up $PROJECT for the $ENV environment..."5. Decision Making: Conditional Logic
Using if-else to handle different outcomes.
#!/bin/bash
read -p "Enter server temperature (Celsius): " TEMP
if [ "$TEMP" -gt 60 ]; then
echo "⚠️ ALERT: Server is overheating! Triggering cooling..."
else
echo "âś… Server temperature is optimal."
fi6. Batch Automation: For Loops
Loops are essential for performing the same task on multiple items.
#!/bin/bash
echo "Creating log backup directories..."
for DIR in logs backups reports scripts; do
echo "Processing: $DIR"
mkdir -p "/tmp/project/$DIR"
done
echo "All directories created in /tmp/project/"7. Dynamic Strings: Command Substitution
Using the output of one command inside another variable or string.
#!/bin/bash
# Count the number of files in the current directory
FILE_COUNT=$(ls -1 | wc -l)
CURRENT_PATH=$(pwd)
echo "You are currently in: $CURRENT_PATH"
echo "Total files found: $FILE_COUNT"[!NOTE] Best Practice: Commenting Notice how each script includes a brief description. Always comment your scripts so your teammates (and "future-you") can understand the logic months later.