How do I delete a Git branch locally and remotely?
To delete a Git branch:
Locally:
git branch -d branch-name # Use -D to force delete
Remotely:
git push origin --delete branch-name
When working with Git, you may need to delete branches that are no longer needed. You can delete a branch both locally and remotely using simple commands.
1. Deleting a Local Branch
git branch -d branch-name
The -d flag deletes the branch but prevents deletion if it has unmerged changes.
If the branch is not fully merged, use:
git branch -D branch-name
This force deletes the branch, even if there are unmerged changes.
2. Deleting a Remote Branch
git push origin --delete branch-name
- This removes the branch from the remote repository.
- Other team members will no longer see this branch when they fetch updates.
3. Removing Deleted Remote Branch Locally
git fetch --prune
Cleans up deleted remote branches from your local Git references.
Important Notes:
You cannot delete the branch youāre currently on, so switch to another branch first:
git checkout main
Be careful when using -D as it permanently removes unmerged work.