[Git] Remove local branches that have been merged

This git command will delete your local branches that have been merged to the main branch.

Git is one of the best and worst parts about software development. Typically during development, you create branches for features or bug fixes and merge them into the main branch. On my team we set Github to automatically delete the remote branch when it's merged into main.

Eventually, when you run git branch you'll see a bunch of branches, but you can't tell which have been merged and which ones haven't. Here's a simple example, where I've merged every branch except the feat/prisma branch:

git branch showing multiple branches

Delete all merged branches:

Now use the following command to delete the branches that have been merged into the main branch.

git branch --merged main | grep -v "^\* main" | xargs -n 1 -r git branch -d

If your main branch is called something other than "main", change the two instances of "main" to whatever your main branch is called.

running the command

This deletes all the branches that have been merged, leaving the only main and the feat/prisma branch that I'm still working on:

git branch showing one branch