Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.4k points)

Is there a simple way to delete all tracking branches whose remote equivalent no longer exists?

Example:

Branches (local and remote)

  • master
  • origin/master
  • origin/bug-fix-a
  • origin/bug-fix-b
  • origin/bug-fix-c

Locally, I only have a master branch. Now I need to work on bug-fix-a, so I check it out, work on it, and push changes to the remote. Next I do the same with bug-fix-b.

Branches (local and remote)

  • master
  • bug-fix-a
  • bug-fix-b
  • origin/master
  • origin/bug-fix-a
  • origin/bug-fix-b
  • origin/bug-fix-c

Now I have local branches master, bug-fix-a, bug-fix-b. The Master branch maintainer will merge my changes into master and delete all branches he has already merged.

So the current state is now:

Branches (local and remote)

  • master
  • bug-fix-a
  • bug-fix-b
  • origin/master
  • origin/bug-fix-c

Now I would like to call some command to delete branches (in this case bug-fix-a, bug-fix-b), which are no longer represented in the remote repository.

It would be something like the existing command git remote prune origin, but more like git local prune origin.

1 Answer

0 votes
by (27.5k points)

Using git remote prune origin will prune tracking branches not on the remote.

Using git branch --merged will list out branches that have been merged into the current branch.

The command xargs git branch -d will delete branches listed on standard input.

But you need to be careful while deleting branches listed by git branch --merged. Keep in mind that this list could include master or other branches you'd prefer not to delete.

In order to give yourself the opportunity to edit the list before deleting branches, you could do the following in one line:

git branch --merged >/tmp/merged-branches && vi /tmp/merged-branches && xargs git branch -d </tmp/merged-branches

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...