How to Delete Already Merged Git Branches
- Steps to deleting already merged branches
Deleting merged branches is something that many developers like to do to keep their git repository clean and easy to browse. Let's find out how to remove branches that have already been merged.
Steps to deleting already merged branches¶
Here are the steps you need to take and get the job done properly:
List all the branches that were merged in the remote.
git branch --merged
There may be some branches that you do not want to delete. Thus, we add a few arguments to exclude master and develop branches. The following command will skip the master branch, and anything that includes dev in it:
git branch --merged | grep -i -v -E "master|dev"
If you want to exclude another branch, add the name to the grep sequence like this:
git branch --merged | grep -i -v -E "master|dev|skip-branch-name"
To delete all local branches that are already merged into the currently checked out branch:
git branch --merged | grep -i -v -E "master|dev"| xargs git branch -d
Deleting local and remote branches¶
Delete a merged local branch by running the git branch command with the -d option. For more detailed information and instructions, you can check out How to Delete Both Local and Remote Branches in Git.
git branch -d <branch-name>
If it's not merged, run:
git branch -D <branch-name>
Delete it from the remote by the git push command with --delete (suppose, the name of remote is origin, which is by default) :
git push --delete origin <branch-name>
As an alternative, you can use the following command:
git push origin :<branch-name>
Deleting remote-tracking branches¶
After deleting the branch from the remote, prune to get rid of remote-tracking branches with the git remote command:
git remote prune origin
or prune individual remote-tracking branches with the git branch -dr command:
git branch -dr <branch-name>
Branches are a pointer to a snapshot of the changes. A new branch is created to encapsulate the changes when you want to fix bugs or add new features helping you to clean up the history before merging it. Branches represent an isolated line of development. They are accepted as a way to request a new working directory, staging area, and project history. Developing isolated lines of development for two features in branches will enable developers to operate on them in parallel and make the master branch free from questionable code.