How to delete a branch locally and in a remote repository?
Deleting branches is a routine task after work is complete. Branches should be deleted both locally and in remote to keep the repository clean.
Local deletion: git branch -d <name> deletes a branch, but only if it's merged with the current one. Git checks that all the branch's commits are in the current branch — if not, it gives an error. This protects against losing work. The command git branch -D <name> deletes forcibly, even if there are unmerged commits. Use -D only if you're sure the changes aren't needed — after deletion, a branch can only be recovered via reflog.
Remote deletion: git push origin --delete <name> deletes a branch on the server (GitHub, GitLab). Shorthand: git push origin :<name>. After deleting a remote branch, other developers will see it as "gone" on their next git fetch.
Deleting tracking branches: after deleting a remote branch, the local tracking copy (origin/<name>) remains. Clean it up: git fetch --prune or git remote prune origin. This removes local references to non-existent remote branches.
Bulk cleanup: git branch --merged main shows branches merged with main — they can be safely deleted. Command to delete all merged branches except main: git branch --merged main | grep -v "main" | xargs git branch -d. Be careful — make sure you don't delete a branch you're working on.
Recovering a deleted branch: git reflog shows the hash of the deleted branch's last commit. Run git branch <name> <hash> — the branch is restored. Reflog keeps history for 90 days, so recovery is possible within that period.
Good practice: delete feature branches immediately after merging into main. This keeps branches clean and eases navigation. On GitHub, you can set up automatic branch deletion after merge: Settings → Options → Automatically delete head branches.