How to Delete a Git Branch Both Locally and Remotely
In most cases, deleting a Git branch is straightforward. This article will guide you on how to remove a Git branch both locally and remotely.
Local Branch
To delete a branch locally, use the following command:
git branch -d localBranchName
Remote Branch
To delete a branch remotely, use this command:
git push origin --delete remoteBranchName
Deleting a Branch Locally
Before deleting a branch locally, ensure you are not currently on the branch you want to delete. Switch to a different branch, such as the main branch:
git checkout main
To delete a branch, use the command:
git branch -d <branch>
For example:
git branch -d fix/authentication
The -d
option deletes the branch if it has been pushed and merged with the remote branch. To force deletion even if it hasn't been pushed or merged, use -D
instead.
The branch is now deleted locally.
Deleting a Branch Remotely
To delete a branch remotely, use the command:
git push <remote> --delete <branch>
For example:
git push origin --delete fix/authentication
Alternatively, you can use a shorter command to delete a branch remotely:
git push <remote> :<branch>
For example:
git push origin :fix/authentication
If you encounter the error below, it may indicate that someone else has already deleted the branch:
error: unable to push to unqualified destination: remoteBranchName
The destination refspec neither matches an existing ref on the remote nor begins with refs/, and we are unable to guess a prefix based on the source ref.
error: failed to push some refs to 'git@repository_name'
To resolve this, synchronize your branch list using:
git fetch -p
The -p
flag stands for "prune." After fetching, branches that no longer exist on the remote will be deleted.
Conclusion
In conclusion, managing Git branches effectively is essential for maintaining a clean and organized codebase. By regularly deleting unused branches both locally and remotely, you can reduce clutter and potential confusion. Make it a habit to remove branches once a feature is completed and merged into the main codebase.