Shell Scripting Dasar — DevOps

Apa itu Shell Script? Shell script adalah file berisi kumpulan command yang dieksekusi secara berurutan. Berguna untuk mengotomasi tugas repetitif seperti…

Apa itu Shell Script?

Shell script adalah file berisi kumpulan command yang dieksekusi secara berurutan. Berguna untuk mengotomasi tugas repetitif seperti deployment, backup, atau setup environment.

Dasar Shell Script

#!/bin/bash
# Shebang line: menentukan interpreter

# Variabel (tanpa spasi di sekitar =)
APP_NAME="my-app"
PORT=3000
echo "Starting $APP_NAME on port $PORT"

# Input dari user
read -p "Enter environment: " ENV
echo "Deploying to $ENV"

Conditional & Loop

# If-else
if [ -f ".env" ]; then
    echo ".env file exists"
elif [ -f ".env.example" ]; then
    cp .env.example .env
    echo "Created .env from example"
else
    echo "No .env file found!"
    exit 1
fi

# Loop
for file in *.log; do
    echo "Processing: $file"
    gzip "$file"
done

# While loop
while ! curl -s http://localhost:3000/health > /dev/null; do
    echo "Waiting for app to start..."
    sleep 2
done
echo "App is ready!"

Contoh: Deploy Script

#!/bin/bash
set -e  # stop jika ada error

APP_DIR="/var/www/my-app"
BRANCH="${1:-main}"  # default ke main

echo "=== Deploying branch: $BRANCH ==="

cd "$APP_DIR"
git fetch origin
git checkout "$BRANCH"
git pull origin "$BRANCH"

# Install dependencies
npm ci --production
php artisan migrate --force

# Restart services
sudo systemctl restart php-fpm
sudo systemctl restart nginx

echo "=== Deploy complete! ==="

Best Practices

Yang akan kamu pelajari