How to delete origin and local branch in Git
Deleting a branch is a bit like taking out the trash: if you only do it in the kitchen (locally), the bin outside (remotely) stays full. To truly clean up your project, you need to perform a two-step operation.
Here is how to safely and effectively wipe a branch from existence both on your machine and on the server.
🏠 1. The Local Cleanup
When you delete a branch locally, Git checks to see if you've merged your work. If you haven't, it will stop you to prevent data loss.
- The Safe Way (
-d): Only deletes the branch if it has been merged into your current HEAD. - The "Force" Way (
-D): Deletes the branch regardless of its merge status. Use this if you started a feature, realized it was a terrible idea, and want to burn the evidence.
☁️ 2. The Remote Cleanup
Deleting a branch on GitHub, GitLab, or Bitbucket doesn't happen automatically when you delete it locally. You have to "push" the deletion to the server.
The modern, readable command for this is:
git push <remote_name> --delete <branch_name>
💻 The "Fresh Start" Workflow
I have combined all the essential commands into this single block. Copy these when you're ready to prune your repository.
# 1. Switch to a branch you ARE NOT deleting (usually main or master)
git checkout main
# 2. Delete the branch locally
# Use -d for merged branches, -D to force delete unmerged ones
git branch -d feature-old-stuff
# 3. Delete the branch on the remote server (usually named 'origin')
git push origin --delete feature-old-stuff
# 4. THE GHOST STEP: Cleanup stale references
# Even after deletion, your local Git might still "remember" the remote branch.
# This command prunes those dead "remote-tracking" references.
git fetch --prune
📊 Summary of Deletion Commands
| Task | Command | When to use it? |
|---|---|---|
| Delete Merged Local | git branch -d <name> | Daily housekeeping. |
| Force Delete Local | git branch -D <name> | When you want to discard work entirely. |
| Delete Remote | git push <remote> -d <name> | When the PR is merged and done. |
| Prune Stale Links | git fetch -p | When git branch -a shows branches that don't exist. |
⚠️ "I deleted the wrong branch! Help!"
If you accidentally deleted a local branch using -D and realized you actually needed that code, don't panic. As long as you haven't run a garbage collection recently, your commits are still in Git's database.
You can find the "lost" commit hash by running:
git reflog
Once you find the hash, you can "revive" the branch with:
git checkout -b <branch_name> <commit_hash>
📚 Sources & Technical Refs
- [1.1] Git SCM Docs: git-branch - Details on the
-dvs-Dflags. - [2.1] GitHub Docs: Deleting branches - Best practices for remote management.
- [3.1] Atlassian Git: Git Delete Branch - A comprehensive guide for beginners.
