Skip to content

Instantly share code, notes, and snippets.

@Thadah
Created January 8, 2025 12:05
Show Gist options
  • Select an option

  • Save Thadah/6a7888d22c4f79055fe6df4f1462a43e to your computer and use it in GitHub Desktop.

Select an option

Save Thadah/6a7888d22c4f79055fe6df4f1462a43e to your computer and use it in GitHub Desktop.
Script to update GIT remotes easily
#!/bin/bash
# Configuration
OLD_DOMAIN="example.com"
NEW_DOMAIN="example.dev"
# Check if REPOS_PATH is provided as an argument
if [ -n "$1" ]; then
REPOS_PATH="$1"
else
echo "Usage: $0 /path/to/repos"
exit 1
fi
# Verify that REPOS_PATH exists and is a directory
if [ ! -d "$REPOS_PATH" ]; then
echo "Error: The path '$REPOS_PATH' does not exist or is not a directory."
exit 1
fi
# Function to update remote URLs in a Git repository
update_remote() {
local repo_path="$1"
echo "Updating repository: $repo_path"
cd "$repo_path" || { echo "Failed to enter directory: $repo_path"; return; }
# Get current remote URL
CURRENT_URL=$(git remote get-url origin 2>/dev/null)
if [ -z "$CURRENT_URL" ]; then
echo "No 'origin' remote found for $repo_path. Skipping."
return
fi
# Check if the current URL contains the old domain
if [[ "$CURRENT_URL" == *"$OLD_DOMAIN"* ]]; then
# Replace old domain with new domain
NEW_URL=${CURRENT_URL//$OLD_DOMAIN/$NEW_DOMAIN}
# Update the remote URL
git remote set-url origin "$NEW_URL"
echo "Updated origin to $NEW_URL"
# Optional: Fetch from the new remote to verify
git fetch origin >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Successfully fetched from the new remote."
else
echo "Warning: Failed to fetch from the new remote. Check your configuration."
fi
else
echo "No matching remote URL found for $repo_path. Skipping."
fi
}
# Export the function so it's available to subshells (used by find -exec)
export -f update_remote
export OLD_DOMAIN
export NEW_DOMAIN
# Use find to locate all .git directories up to depth 5 and update their remotes
find "$REPOS_PATH" -type d -name ".git" -maxdepth 5 | while read -r git_dir; do
repo_dir=$(dirname "$git_dir")
update_remote "$repo_dir"
done
echo "Remote URLs update process completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment