← Back to all snippets
BASH

Automate Git Pull and Service Restart for Web Deployment

A concise bash script to pull the latest changes from a Git repository, optionally install dependencies, and restart a specified web service, ideal for simple CI/CD or manual deployments.

#!/bin/bash

# Configuration
PROJECT_DIR="/var/www/mywebapp" # Absolute path to your web application directory
GIT_BRANCH="main"             # The Git branch to pull from
SERVICE_NAME="mywebapp.service" # The name of your systemd service (e.g., nginx, apache2, gunicorn, myapp.service)

echo "Starting deployment for $PROJECT_DIR on branch $GIT_BRANCH..."

# Navigate to project directory
cd "$PROJECT_DIR" || { echo "Error: Project directory not found. Exiting."; exit 1; }

# Pull latest changes from Git
echo "Pulling latest changes from Git..."
git pull origin "$GIT_BRANCH" || { echo "Error: Git pull failed. Exiting."; exit 1; }

# Optional: Install or update application dependencies (uncomment and adjust as needed)
# echo "Installing Node.js dependencies..."
# npm install --production || { echo "Error: npm install failed. Exiting."; exit 1; }

# echo "Installing PHP Composer dependencies..."
# composer install --no-dev --optimize-autoloader || { echo "Error: Composer install failed. Exiting."; exit 1; }

# Restart web service
echo "Restarting $SERVICE_NAME..."
sudo systemctl restart "$SERVICE_NAME" || { echo "Error: Service restart failed. Check service name and permissions. Exiting."; exit 1; }

echo "Deployment complete."
How it works: This script automates a common web deployment task: pulling the latest code from a Git repository and restarting an associated web service. It navigates to the project directory, performs a `git pull` on the specified branch, and then restarts the application's systemd service. Optional sections are included for dependency installation (e.g., Node.js with `npm install` or PHP with `composer install`), making it a flexible starting point for basic CI/CD pipelines or manual server updates.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs