Skip to content

Instantly share code, notes, and snippets.

@Git-on-my-level
Last active August 14, 2025 11:40
Show Gist options
  • Select an option

  • Save Git-on-my-level/c0f77212a6bf54d2ac5cb121a251ac68 to your computer and use it in GitHub Desktop.

Select an option

Save Git-on-my-level/c0f77212a6bf54d2ac5cb121a251ac68 to your computer and use it in GitHub Desktop.
Update `main` for multiple git repositories in the current directory
#!/bin/bash
# Initialize arrays to store results
successful_updates=()
failed_updates=()
skipped_repos=()
no_git_repos=()
# Get the current directory
current_dir=$(pwd)
# Find all immediate subdirectories
for dir in */; do
# Check if it's a directory
if [ -d "$dir" ]; then
echo "Processing $dir..."
cd "$dir" || continue
# Check if it's a git repository
if [ -d ".git" ]; then
# Fetch the latest from origin
if ! git fetch origin >/dev/null 2>&1; then
failed_updates+=("$dir (could not fetch)")
cd "$current_dir" || exit
continue
fi
# Get the current branch name
current_branch=$(git rev-parse --abbrev-ref HEAD)
if [ "$current_branch" != "main" ]; then
if ! git checkout main >/dev/null 2>&1; then
failed_updates+=("$dir (could not switch to main)")
cd "$current_dir" || exit
continue
fi
fi
# Now on main branch, check for uncommitted changes
if ! git diff-index --quiet HEAD --; then
skipped_repos+=("$dir (uncommitted changes)")
else
# Check if local main is behind remote main
if [ "$(git rev-parse HEAD)" != "$(git rev-parse origin/main)" ]; then
if ! git pull origin main --ff-only >/dev/null 2>&1; then
failed_updates+=("$dir (pull failed)")
else
successful_updates+=("$dir")
fi
else
successful_updates+=("$dir (already up-to-date)")
fi
fi
else
no_git_repos+=("$dir")
fi
cd "$current_dir" || exit
fi
done
# Print summary
echo ""
_GREEN='\033[0;32m'
_RED='\033[0;31m'
_YELLOW='\033[0;33m'
_BLUE='\033[0;34m'
_NC='\033[0m' # No Color
echo -e "${_BLUE}--- Git Repository Update Summary ---${_NC}"
echo ""
if [ ${#successful_updates[@]} -gt 0 ]; then
echo -e "${_GREEN}<E2><9C><85> Successful Updates:${_NC}"
for repo in "${successful_updates[@]}"; do
echo -e " - $repo"
done
echo ""
fi
if [ ${#failed_updates[@]} -gt 0 ]; then
echo -e "${_RED}<E2><9D><8C> Failed Updates (require manual inspection):${_NC}"
for repo in "${failed_updates[@]}"; do
echo -e " - $repo"
done
echo ""
fi
if [ ${#skipped_repos[@]} -gt 0 ]; then
echo -e "${_YELLOW}<E2><9A><A0><EF><B8><8F> Skipped Repositories:${_NC}"
for repo in "${skipped_repos[@]}"; do
echo -e " - $repo"
done
echo ""
fi
if [ ${#no_git_repos[@]} -gt 0 ]; then
echo -e "${_BLUE}<E2><84><B9><EF><B8><8F> Not Git Repositories:${_NC}"
for repo in "${no_git_repos[@]}"; do
echo -e " - $repo"
done
fi
echo -e "${_BLUE}--- Finished ---${_NC}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment