#!/bin/bash REPO_URL="https://github.com/your-org/your-repo.git" # Replace with your repository URL TARGET_DIR="/srv/www/my-app" # Replace with your deployment target directory BRANCH="main" # Replace with your target branch # --- Configuration for Error Handling (similar to previous snippet) --- set -e set -u set -o pipefail log() { local type="$1" local message="$2" echo "$(date '+%Y-%m-%d %H:%M:%S') [GIT_DEPLOY] [${type}] ${message}" } error_exit() { log "ERROR" "An error occurred. Exiting." exit 1 } trap 'error_exit' ERR # --- Main Logic --- log "INFO" "Starting Git deployment process for ${REPO_URL} on branch ${BRANCH}." # Check if target directory exists and is a git repository if [ -d "${TARGET_DIR}" ]; then if [ -d "${TARGET_DIR}/.git" ]; then log "INFO" "Repository already exists at ${TARGET_DIR}. Pulling latest changes..." cd "${TARGET_DIR}" git fetch origin git reset --hard "origin/${BRANCH}" # Ensures local matches remote, discards local changes # Alternative: git pull origin ${BRANCH} (if local changes are allowed or handled elsewhere) log "INFO" "Repository updated." else log "ERROR" "${TARGET_DIR} exists but is not a Git repository. Please ensure it's empty or remove it." exit 1 fi else log "INFO" "Target directory ${TARGET_DIR} does not exist. Cloning repository..." mkdir -p "${TARGET_DIR}" git clone --branch "${BRANCH}" "${REPO_URL}" "${TARGET_DIR}" log "INFO" "Repository cloned into ${TARGET_DIR}." fi # Optional: Perform post-deployment steps (e.g., install dependencies, restart services) log "INFO" "Running post-deployment steps (e.g., npm install, service restart)..." cd "${TARGET_DIR}" # Example: Install Node.js dependencies # if [ -f "package.json" ]; then # npm install --production # log "INFO" "Node.js dependencies installed." # fi # Example: Restart a service (e.g., Nginx, Gunicorn, PHP-FPM) # sudo systemctl restart your_web_app_service log "INFO" "Post-deployment steps completed." log "INFO" "Git deployment process finished successfully for ${TARGET_DIR}."