Deleting Specific Local Branches
In addition to deleting merged and unmerged local branches, you may sometimes need to delete specific branches based on their names or other criteria. Git provides various options to help you achieve this.
Deleting a Branch by Name
To delete a specific local branch by its name, you can use the following command:
git branch -d <branch-name>
Replace <branch-name>
with the name of the branch you want to delete.
Example:
git branch -d feature-xyz
As mentioned earlier, if the branch has not been merged, Git will display a warning and refuse to delete the branch. You can use the -D
option to force the deletion.
Deleting Branches Matching a Pattern
If you want to delete multiple local branches that match a specific pattern, you can use the following command:
git branch | grep -E '<pattern>' | xargs git branch -d
Replace <pattern>
with the regular expression pattern that matches the branch names you want to delete.
Example:
git branch | grep -E '^fix-' | xargs git branch -d
This command will delete all local branches whose names start with fix-
.
Deleting Branches Based on Age
You can also delete local branches based on their age, which can be useful when cleaning up old or stale branches. To delete local branches that are older than a certain number of days, you can use the following command:
git branch --merged | grep -E '^[^*]' | xargs -r git branch -d
This command will delete all local branches that have been merged into the current branch and are older than the specified number of days.
By using these various options, you can effectively delete specific local Git branches based on your needs, keeping your repository clean and organized.