BASH
Automating Git Pull and Build on a Server
A bash script to automate pulling the latest code from a Git repository, installing dependencies, and building a web project on a remote server for deployments.
#!/bin/bash
# Configuration
REPO_DIR="/var/www/mywebapp"
GIT_BRANCH="main"
# Navigate to repository directory
echo "Navigating to repository directory..."
cd "$REPO_DIR" || {
echo "Error: Repository directory '$REPO_DIR' not found. Aborting."
exit 1
}
# Pull latest changes
echo "Pulling latest changes from Git branch $GIT_BRANCH..."
git pull origin "$GIT_BRANCH" || {
echo "Error: Failed to pull latest changes from Git. Aborting."
exit 1
}
# Install Node.js dependencies (adjust for your project, e.g., yarn install)
echo "Installing Node.js dependencies..."
npm install || {
echo "Error: Failed to install dependencies. Aborting."
exit 1
}
# Build project (adjust for your project, e.g., yarn build, composer install)
echo "Building project..."
npm run build || {
echo "Error: Failed to build project. Aborting."
exit 1
}
echo "Deployment successful!"
# Optional: Restart a service if necessary (e.g., systemctl restart mywebapp)
How it works: This script streamlines web application deployments by navigating to a specified project directory, pulling the latest code from a Git branch, installing project dependencies (e.g., Node.js packages), and then executing the project's build command. It includes robust error handling at each critical step to ensure failures are caught, making it suitable for basic CI/CD pipelines or manual server updates.