Bash Scripting — Server Automation

লেসন ১২ / ৩৮

📜 Basics

#!/bin/bash
# script.sh

echo "Hello $USER!"
echo "Date: $(date)"

chmod +x script.sh
./script.sh

🔢 Variables

NAME="Alice"
echo "Hello ${NAME}"

DATE=$(date +%Y-%m-%d)
read -p "Enter name: " NM

# Args
$0 = script
$1 = first arg
$@ = all
$# = count

🔀 Conditional

if [ "$1" = "start" ]; then
    echo "starting"
elif [ "$1" = "stop" ]; then
    echo "stopping"
else
    echo "Usage: $0 {start|stop}"
    exit 1
fi

# File checks
[ -f "/etc/nginx.conf" ]       # file exists
[ -d "/var/www" ]              # dir exists
[ -z "$VAR" ]                  # empty
[ -n "$VAR" ]                  # not empty

# Number: -eq -ne -lt -le -gt -ge
[ $AGE -gt 18 ]

🔁 Loops

for i in {1..10}; do echo $i; done

for file in /var/www/*.php; do
    echo "$file"
done

while [ $COUNT -lt 5 ]; do
    COUNT=$((COUNT + 1))
done

# Read file lines
while IFS= read -r line; do
    echo "$line"
done < input.txt

🛠️ Functions

backup_db() {
    local DB=$1
    mysqldump -uroot -p$DB_PASS $DB > /backup/$DB.sql
    if [ $? -eq 0 ]; then
        echo "✅ $DB"
        return 0
    fi
    return 1
}
backup_db "myapp"

⚠️ Error Handling

set -euo pipefail   # 🔥 always

# Trap
trap "rm -f /tmp/lock" EXIT

# Check command exists
if ! command -v docker &> /dev/null; then
    echo "Docker missing"
    exit 1
fi

📋 Production Scripts

1. Auto Backup

#!/bin/bash
set -euo pipefail
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p /backup

mysqldump --all-databases -uroot -p$MYSQL_PASS \
  | gzip > /backup/db_$DATE.sql.gz

tar czf /backup/www_$DATE.tar.gz /var/www

aws s3 cp /backup/db_$DATE.sql.gz s3://my-backup/

find /backup -mtime +7 -delete

2. Health Check

#!/bin/bash
URL="https://example.com/health"
CODE=$(curl -s -o /dev/null -w "%{http_code}" $URL)
if [ "$CODE" != "200" ]; then
    curl -X POST $SLACK_WEBHOOK \
      -d "{\"text\":\"Site DOWN $CODE\"}"
    exit 1
fi

3. Log Cleaner

#!/bin/bash
find /var/log/myapp -name "*.log" -mtime +30 -exec gzip {} \;
find /var/log/myapp -name "*.log.gz" -mtime +90 -delete

📚 Best Practice

  • Always set -euo pipefail
  • Quote variables: "$VAR"
  • shellcheck (lint)
  • Log everything
  • Functions for reuse

🎓 মূল কথা ⭐

Bash automation gold। 50-line script = 10 hour manual work। Cron schedule → server auto-pilot। Complex logic → Python; simple ops → Bash।