Sync all Git branches with remote

Posted at (134 words, 1 minute to read)
Tags: ,

Sometimes there is no good internet connection, but you can still work at your laptop (merge PR, etc). It’s very handy to have a local full local copy of the Git repository of a project on your computer for this purpose.

Unfortunately, Git itself doesn’t have out-of-the-box functionality to sync your local repository with a central server (like Github).

I searched for a solution on stackoverflow, but surprisingly there are only separate commands to do different parts of this task.

So I made this little script in bash to be able to do this synchronisation.

#!/usr/bin/env bash

# Debug: Print all commands with expanded variables
# set -x

# Get all remote refs & remove outdated local refs
git fetch --all --prune

# Create local copy of remote branch & load latest changes
for rb in `git branch --remotes | grep -v 'HEAD'`; do
  lb=${rb#origin/}
  echo "$rb -> $lb"
  git branch --track $lb $rb 2>/dev/null
  git fetch --update-head-ok origin $lb:$lb
done

# Remove all merged local branches
git branch --merged | xargs echo | grep -v '^*\|^main$\|^develop$|^stage$' | xargs git branch -d

Note: On line 18 you can specify a list of branches that should always remain local.

This script will also be useful if you often have to check other branches manually before merging them.

Installation & Run:

curl https://gist.githubusercontent.com/vladkens/5261c703111fd1d0a870c3bf5e53c698/raw/698af0fdac327bcb3b7d8777a4593a4d66321bb6/git-sync.sh > git-sync.sh
chmod +x git-sync.sh

./git-sync.sh