Deleting a Local Git Branch
Deleting a local Git branch is a common task when you've finished working on a feature or bug fix and want to clean up your local repository. Here's how you can do it:
Deleting a Single Branch
To delete a single local branch, use the git branch -d
command followed by the name of the branch you want to delete:
git branch -d feature/new-functionality
If the branch has already been merged into another branch, Git will allow you to delete it. However, if the branch has not been merged, Git will prevent you from deleting it to avoid losing any committed changes. In this case, you can use the -D
flag to force the deletion:
git branch -D feature/experimental-change
Deleting Multiple Branches
If you want to delete multiple local branches at once, you can use the git branch -d
or git branch -D
command with the -a
flag to list all the branches, and then select the ones you want to delete:
git branch -a
git branch -d branch1 branch2 branch3
This will delete the specified branches from your local repository.
Checking Merged Branches
Before deleting a branch, it's a good practice to check which branches have been merged into the main branch. You can do this using the git branch --merged
command:
git branch --merged
This will list all the branches that have been merged into the current branch. Branches that are listed here can be safely deleted, as they no longer contain any unique commits.
Deleting Remote Branches
If you've already pushed a local branch to a remote repository, you can delete the remote branch using the git push
command with the -d
or --delete
option:
git push origin --delete feature/old-functionality
This will delete the feature/old-functionality
branch from the remote repository.