DocumentationBash Scripts

Bash Script

Common DevOps Scripts

Server Update & Upgrade

#!/bin/bash
# update-system.sh - Update and upgrade system packages
 
set -e  # Exit on error
 
echo "Updating package lists..."
sudo apt update
 
echo "Upgrading packages..."
sudo apt upgrade -y
 
echo "Removing unused packages..."
sudo apt autoremove -y
sudo apt autoclean -y
 
echo "System update complete!"

Install Multiple Services

#!/bin/bash
# install-stack.sh - Install Node.js, Nginx, PostgreSQL, Redis
 
set -e
 
# Update system
echo "Updating system..."
sudo apt update
sudo apt upgrade -y
 
# Install Node.js
echo "Installing Node.js..."
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install nodejs -y
 
# Install Nginx
echo "Installing Nginx..."
sudo apt install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
 
# Install PostgreSQL
echo "Installing PostgreSQL..."
sudo apt install postgresql postgresql-contrib -y
sudo systemctl start postgresql
sudo systemctl enable postgresql
 
# Install Redis
echo "Installing Redis..."
sudo apt install redis-server -y
sudo systemctl start redis-server
sudo systemctl enable redis-server
 
echo "Installation complete!"
echo "Node.js: $(node --version)"
echo "Nginx: $(nginx -v 2>&1)"
echo "PostgreSQL: $(psql --version)"
echo "Redis: $(redis-cli --version)"

Docker Installation

#!/bin/bash
# install-docker.sh - Install Docker and Docker Compose
 
set -e
 
echo "Installing Docker dependencies..."
sudo apt update
sudo apt install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg \
    lsb-release
 
echo "Adding Docker GPG key..."
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
 
echo "Adding Docker repository..."
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
 
echo "Installing Docker..."
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io docker-compose-plugin -y
 
echo "Adding user to docker group..."
sudo usermod -aG docker $USER
 
echo "Installing Docker Compose..."
sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
 
echo "Docker installation complete!"
docker --version
docker-compose --version

Application Deployment

#!/bin/bash
# deploy.sh - Deploy application from Git
 
set -e
 
APP_DIR="/var/www/myapp"
REPO_URL="https://github.com/user/myapp.git"
BRANCH="main"
 
echo "Deploying application..."
 
# Clone or pull repository
if [ -d "$APP_DIR/.git" ]; then
    echo "Pulling latest code..."
    cd $APP_DIR
    git pull origin $BRANCH
else
    echo "Cloning repository..."
    git clone -b $BRANCH $REPO_URL $APP_DIR
    cd $APP_DIR
fi
 
# Install dependencies
echo "Installing dependencies..."
npm install
 
# Build application
echo "Building application..."
npm run build
 
# Restart application
echo "Restarting application..."
sudo systemctl restart myapp
 
echo "Deployment complete!"

Backup Script

#!/bin/bash
# backup.sh - Backup important directories and databases
 
set -e
 
BACKUP_DIR="/backups"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/backup_$DATE.tar.gz"
 
echo "Starting backup..."
 
# Create backup directory
mkdir -p $BACKUP_DIR
 
# Backup application code
echo "Backing up application..."
tar -czf "$BACKUP_DIR/app_$DATE.tar.gz" /var/www/myapp
 
# Backup database
echo "Backing up PostgreSQL database..."
pg_dump -U postgres mydb | gzip > "$BACKUP_DIR/db_$DATE.sql.gz"
 
# Backup Nginx config
echo "Backing up Nginx configuration..."
tar -czf "$BACKUP_DIR/nginx_$DATE.tar.gz" /etc/nginx
 
# Keep only last 7 days of backups
echo "Cleaning old backups..."
find $BACKUP_DIR -type f -mtime +7 -delete
 
echo "Backup complete! Size: $(du -sh $BACKUP_DIR | cut -f1)"

Health Check Script

#!/bin/bash
# health-check.sh - Check service health
 
set -e
 
echo "=== System Health Check ==="
 
# Check disk space
echo -e "\n--- Disk Space ---"
df -h | head -n 5
 
# Check memory
echo -e "\n--- Memory Usage ---"
free -h
 
# Check running services
echo -e "\n--- Service Status ---"
systemctl is-active --quiet docker && echo "✓ Docker: Running" || echo "✗ Docker: Stopped"
systemctl is-active --quiet nginx && echo "✓ Nginx: Running" || echo "✗ Nginx: Stopped"
systemctl is-active --quiet postgresql && echo "✓ PostgreSQL: Running" || echo "✗ PostgreSQL: Stopped"
 
# Check application
echo -e "\n--- Application Health ---"
curl -s http://localhost:3000/health || echo "✗ Application: Not responding"
 
# Check database connection
echo -e "\n--- Database Connection ---"
pg_isready -h localhost || echo "✗ PostgreSQL: Not responding"
 
echo -e "\nHealth check complete!"

Log Rotation Script

#!/bin/bash
# rotate-logs.sh - Rotate and archive logs
 
set -e
 
LOG_DIR="/var/log/myapp"
ARCHIVE_DIR="/var/log/myapp/archive"
MAX_SIZE=10485760  # 10MB in bytes
 
mkdir -p $ARCHIVE_DIR
 
for logfile in $LOG_DIR/*.log; do
    if [ -f "$logfile" ]; then
        size=$(stat -f%z "$logfile" 2>/dev/null || stat -c%s "$logfile" 2>/dev/null)
        
        if [ $size -gt $MAX_SIZE ]; then
            timestamp=$(date +%Y%m%d_%H%M%S)
            gzip -c "$logfile" > "$ARCHIVE_DIR/$(basename $logfile).$timestamp.gz"
            > "$logfile"  # Clear log file
            echo "Rotated: $(basename $logfile)"
        fi
    fi
done
 
echo "Log rotation complete!"

Monitoring & Alerting Script

#!/bin/bash
# monitor.sh - Monitor system and send alerts
 
CPU_THRESHOLD=80
MEM_THRESHOLD=80
DISK_THRESHOLD=90
 
# Check CPU usage
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print 100 - $8}' | cut -d'.' -f1)
if [ $cpu_usage -gt $CPU_THRESHOLD ]; then
    echo "ALERT: High CPU usage: $cpu_usage%" | mail -s "Alert" [email protected]
fi
 
# Check memory usage
mem_usage=$(free | grep Mem | awk '{print int($3/$2 * 100)}')
if [ $mem_usage -gt $MEM_THRESHOLD ]; then
    echo "ALERT: High memory usage: $mem_usage%" | mail -s "Alert" [email protected]
fi
 
# Check disk usage
disk_usage=$(df / | tail -1 | awk '{print $5}' | cut -d'%' -f1)
if [ $disk_usage -gt $DISK_THRESHOLD ]; then
    echo "ALERT: High disk usage: $disk_usage%" | mail -s "Alert" [email protected]
fi
 
echo "Monitoring check complete"

Script Best Practices

# Use shebang
#!/bin/bash
 
# Set error handling
set -e              # Exit on error
set -u              # Exit on undefined variable
set -o pipefail     # Exit on pipe failure
 
# Use functions for reusability
function log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}
 
# Use variables for paths
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
APP_DIR="/var/www/myapp"
 
# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "This script must be run as root" 
    exit 1
fi
 
# Validate arguments
if [ $# -lt 1 ]; then
    echo "Usage: $0 <argument>"
    exit 1
fi
 
# Use proper quoting
"$variable"
 
# Use conditional properly
if [ -f "$file" ]; then
    echo "File exists"
fi

Scheduling Scripts (Cron)

# Add to crontab
crontab -e
 
# Examples:
# Run daily at 2 AM
0 2 * * * /usr/local/bin/backup.sh
 
# Run every hour
0 * * * * /usr/local/bin/health-check.sh
 
# Run every 15 minutes
*/15 * * * * /usr/local/bin/monitor.sh
 
# Run every Monday at 3 AM
0 3 * * 1 /usr/local/bin/weekly-maintenance.sh
 
# View crontab
crontab -l
 
# Remove crontab
crontab -r