Git by Example: Branch Deletion
Learn how to delete local and remote branches. This example covers safe deletion, forced deletion, and removing branches from the remote server.
Code
# 1. Delete a local branch (safe mode)
git branch -d feature-login
# Output (if merged):
# Deleted branch feature-login (was 1a2b3c).
# Output (if NOT merged):
# error: The branch 'feature-login' is not fully merged.
# If you are sure you want to delete it, run 'git branch -D feature-login'.
# 2. Force delete a local branch (unmerged)
git branch -D feature-login
# 3. Delete a remote branch
git push origin --delete feature-loginExplanation
Branches are meant to be temporary workspaces. Once a feature is merged into the main codebase, the branch should typically be deleted to keep the repository clean and manageable. Git provides separate commands for deleting local branches and remote branches.
To delete a local branch, you use git branch -d <branch>. Git includes a safety check: it will prevent you from deleting a branch if it contains commits that haven't been merged into your current branch. This prevents accidental loss of work. If you are sure you want to delete an unmerged branch (e.g., a failed experiment), you can use the capital -D flag to force deletion.
Deleting a local branch does not delete it from the remote server (like GitHub). To remove the remote version, you must use a push command: git push origin --delete <branch>. This tells the remote server to remove its reference to that branch.
- Use
-dfor safe local deletion - Use
-Dto force delete unmerged branches - Deleting local does not delete remote
- Use
git push --deletefor remote

