How to Prune Local Branches in Git

Ashok Chapagai Feb 02, 2024
How to Prune Local Branches in Git

Let’s say your project has many branches that were created in local machine, but do not exist in the remote repository. You can easily remove all the local branches that are out of sync to the remote repository but before doing that, you might want to check all the branches that are available in your local machine, you can run git branch.

Now, to list all the remote branches, you can use git branch -r command. To achieve both result in one single command, you can use git branch -a command. With the branches confirmed, you can proceed with the rest of the article.

Remove (Prune) Local Branches in Git

You can run following command with ease to prune tracking branches that are not on the remote repository.

git remote prune origin

The command above prunes tracking branches not on the remote repository, however the local branch is not deleted yet. To actually delete local branches, you might need to go extra steps explained below.

  • List out all the branches with verbose output,
    git branch -vv
    

    Now, you pipe out the output to grep for origin/.* : gone] since the gone status is put to the branches that are not available in the remote repository but are available in local machine.

    grep 'origin/.*: gone]'
    
  • Again you pipe the output to awk ( which is a very good tool to format ) as below.
    awk '{print $1}'
    
  • Finally, you want to pipe the output to xargs which can be used when you need to take the output from one command and use it as argument to another. You are not to pass the output from Step 2 to git branch -d command to delete the local branches as below.
    xargs git branch -d 
    

Hence, the final two liner command to prune and delete all the local branches that are not available in remote repository is below.

git remote prune origin

After running the command above, you might want to run the command below to achieve the deletion of the local branches that are not available in remote repository.

git branch -vv | grep 'origin/.*: gone]' | awk '{print $1}' | xargs git branch -d
Ashok Chapagai avatar Ashok Chapagai avatar

Ashok is an avid learner and senior software engineer with a keen interest in cyber security. He loves articulating his experience with words to wider audience.

LinkedIn GitHub

Related Article - Git Prune