← Back to all snippets
BASH

Automate Git Pull for Multiple Repositories

Streamline your development workflow by automating 'git pull' across all your Git repositories within a specified directory to keep them up-to-date.

#!/bin/bash

# Define the base directory containing your Git repositories
BASE_DIR="$HOME/projects"

# Check if the directory exists
if [ ! -d "$BASE_DIR" ]; then
  echo "Error: Directory '$BASE_DIR' not found." >&2
  exit 1
fi

echo "Updating all Git repositories in $BASE_DIR..."

# Iterate through each subdirectory in the base directory
for repo_dir in "$BASE_DIR"/*/; do
  # Check if it's a valid directory
  if [ -d "$repo_dir" ]; then
    # Check if it's a Git repository
    if [ -d "$repo_dir/.git" ]; then
      echo "
--- Entering $(basename "$repo_dir") ---"
      (cd "$repo_dir" && git pull)
      if [ $? -ne 0 ]; then
        echo "Error pulling repository: $(basename "$repo_dir")" >&2
      fi
    else
      echo "Skipping $(basename "$repo_dir"): Not a Git repository."
    fi
  fi
done

echo "
All Git repositories updated."
How it works: This script automates updating multiple Git repositories. It defines a base directory, then iterates through each subdirectory. For each subdirectory, it checks if it's a Git repository by looking for the '.git' folder. If it is, the script changes into that directory and executes 'git pull' to fetch and merge changes from the remote. This saves time when working with many projects, ensuring all local copies are synchronized.

Need help integrating this into your project?

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

Hire DigitalCodeLabs