Over time, you may accumulate local branches that you no longer need. Deleting these branches can help keep your repository clean and manageable. This guide will provide a comprehensive overview of how to delete a local branch in Git, along with other related operations.
Basic command to delete a local branch
To delete a local branch in Git, you can use the git branch
command with the -d
option, which stands for --delete. This is the safest method as it prevents you from deleting a branch with unmerged changes.
Syntax and usage
To delete a local branch using the -d
flag, run:
git branch -d <branch_name>
Replace <branch_name>
with the name of the branch you want to delete.
Example
To delete a branch named feature-x
, you would run:
git branch -d feature-x
If the branch has changes that haven't been merged yet, ie. if you have local changes that you have yet to push to the remote repository, Git will block the deletion and display an error message.
Forcing deletion of a local branch
If you're sure that you want to delete a branch regardless of its merge status, you can use the -D
option, which is a shorthand for --delete --force
.
Example
git branch -D feature-x
This command forces the deletion of feature-x
, even if it has unmerged changes.
Deleting all local branches except main
In some cases, you might want to delete all local branches except the main branch. This is extreme but useful in certain scenarios like after completion of a project.
Command to keep main and delete others
git branch | grep -v 'main' | xargs git branch -D
This command lists all branches, filters out the main branch, and forcefully deletes the rest.
For further reading on Git branch management, see the official Git documentation.