Pull all remote git branches to local

Used this when moving away from a git repository that it wasn’t possibly to transfer. Unfortunately the repository had a lot branches that I wanted to keep a copy of just in case.

So I used the following bash script to pull them all down locally so I had a backup.


# Clone the repository
git clone [email protected]:username/repository.git

# Navigate into the repository
cd repository.git

# Fetch all branches
git fetch --all

# For each remote branch
for branch in `git branch -r | grep -v HEAD`;do
    # Get the name of the branch without the "origin/" prefix
    name=`echo $branch | cut -d/ -f2-`

    # Create and checkout local branch
    git checkout -b $name $branch

Just replace username and repository with the actual username and repository name.

Save this script to a .sh file, give it execute permissions with chmod +x scriptname.sh, and then run it with ./scriptname.sh.