Docs / Linux Basics / Essential Shell Scripting for Server Administration

Essential Shell Scripting for Server Administration

By Admin · Feb 25, 2026 · Updated Apr 23, 2026 · 32 views · 1 min read

Script Basics

#!/bin/bash
# Always start with shebang line
# Make executable: chmod +x script.sh

Variables

NAME="webserver"
PORT=8080
echo "Starting $NAME on port $PORT"

# Command substitution
CURRENT_DATE=$(date +%Y-%m-%d)
IP_ADDRESS=$(hostname -I | awk '{print $1}')

Conditionals

# File checks
if [ -f "/etc/nginx/nginx.conf" ]; then
    echo "Nginx config exists"
fi

# String comparison
if [ "$1" = "start" ]; then
    echo "Starting..."
elif [ "$1" = "stop" ]; then
    echo "Stopping..."
else
    echo "Usage: $0 {start|stop}"
    exit 1
fi

# Numeric comparison
if [ $(df / | awk 'NR==2 {gsub(/%/,"",$5); print $5}') -gt 85 ]; then
    echo "WARNING: Disk usage above 85%"
fi

Loops

# Iterate over files
for file in /var/log/*.log; do
    echo "Processing: $file"
    wc -l "$file"
done

# Iterate over servers
for server in web1 web2 db1; do
    ssh "$server" "uptime"
done

# While loop
while true; do
    curl -s -o /dev/null -w "%{http_code}" https://example.com
    sleep 60
done

Functions

log() {
    echo "[$(date +%Y-%m-%d\ %H:%M:%S)] $1" >> /var/log/myscript.log
}

check_service() {
    if systemctl is-active --quiet "$1"; then
        log "$1 is running"
    else
        log "$1 is DOWN — restarting"
        systemctl restart "$1"
    fi
}

check_service nginx
check_service mariadb

Was this article helpful?