0
0
Gitdevops~5 mins

Deleting branches in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you finish working on a feature or fix and want to clean up your project by removing branches you no longer need. Deleting branches helps keep your project tidy and avoids confusion.
After merging a feature branch into the main branch to keep the branch list clean
When a branch was created by mistake and is no longer needed
To remove old branches that are no longer active or maintained
When cleaning up remote branches that have been deleted locally
To avoid clutter in your branch list and reduce mistakes
Commands
This command deletes the local branch named 'feature-login' if it has been fully merged. It helps clean up branches safely.
Terminal
git branch -d feature-login
Expected OutputExpected
Deleted branch feature-login (was 1a2b3c4).
-d - Deletes a branch only if it is fully merged
This command force deletes the local branch 'feature-login' even if it has unmerged changes. Use with caution to avoid losing work.
Terminal
git branch -D feature-login
Expected OutputExpected
Deleted branch feature-login (was 1a2b3c4).
-D - Force deletes a branch regardless of merge status
This command deletes the remote branch 'feature-login' from the remote repository named 'origin'. It cleans up branches on the server.
Terminal
git push origin --delete feature-login
Expected OutputExpected
To https://github.com/example/repo.git - [deleted] feature-login
--delete - Deletes the specified branch on the remote repository
This command lists all local and remote branches so you can verify which branches exist after deletion.
Terminal
git branch -a
Expected OutputExpected
main develop remotes/origin/main remotes/origin/develop
-a - Shows all branches, local and remote
Key Concept

If you remember nothing else, remember: use '-d' to safely delete merged branches and '--delete' to remove branches from the remote repository.

Common Mistakes
Trying to delete a branch with 'git branch -d' before it is merged
Git will refuse to delete the branch to prevent losing unmerged work
Either merge the branch first or use 'git branch -D' to force delete if you are sure
Deleting a remote branch by deleting the local branch only
The remote branch still exists and can cause confusion or conflicts
Use 'git push origin --delete branch-name' to remove the branch from the remote
Force deleting branches without checking their status
You may lose important unmerged changes permanently
Always check branch status and merge state before using '-D'
Summary
Use 'git branch -d branch-name' to safely delete a local branch that is merged.
Use 'git branch -D branch-name' to force delete a local branch regardless of merge status.
Use 'git push origin --delete branch-name' to delete a branch from the remote repository.
Use 'git branch -a' to list all branches and verify deletions.