Search code examples
gitgit-reset

How can I reset hard all branches in git


How do I reset my all local branches, one time to be just like the branches in the remote repository?

I have 42 branches in my local repository, but I have just 21 branches in my remote repository. I don't need the other branches, I just need the 21 branches (with same name in local and remote).

I know

git fetch origin 
git reset --hard origin/master

but I want all 21 branches to together reset hard to the state in origin, and all other branches deleted that are not in origin.


Solution

  • You can use shell scripting if you are on Unix.

    This will first delete all your local branches, and then create all branches from origin.

    # make sure we are currently on no branch, so every branch can be deleted
    git checkout --detach master
    
    # delete all local branches
    git branch | grep -v "HEAD detached" | xargs git branch -D
    
    # re-create all branches from origin
    while read b; do git branch ${b#origin/} $b; done < <(git branch -r | grep 'origin/')
    
    # check out the new master
    git checkout master