BudiBadu Logo
Samplebadu

Git by Example: Branch Deletion

2.43.0

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-login

Explanation

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 -d for safe local deletion
  • Use -D to force delete unmerged branches
  • Deleting local does not delete remote
  • Use git push --delete for remote

Code Breakdown

2
Attempts to delete the branch safely. It will fail if the branch has unmerged changes.
13
Forces the deletion of the branch, even if it contains unmerged work. Use this when you want to discard an experiment.
16
Sends a command to the remote server 'origin' to delete the specified branch there.