How do I delete a Git branch locally and remotely?

To delete a Git branch locally and remotely, use the following commands:

1. Delete a Local Branch

git branch -d <branch_name>      # Delete a merged branch (safe)
git branch -D <branch_name>      # Force-delete an unmerged branch

Example:

git branch -d feature/login       # Delete the merged "feature/login" branch
git branch -D hotfix/crash        # Force-delete the unmerged "hotfix/crash" branch

2. Delete a Remote Branch

git push origin --delete <branch_name>   # Modern syntax
# OR
git push origin :<branch_name>           # Older syntax (colon before branch name)

Example:

git push origin --delete feature/login   # Delete the remote "feature/login" branch

3. Clean Up Local References (Optional)

After deleting a remote branch, prune stale references:

git fetch --prune      # Remove references to deleted remote branches
# OR
git remote prune origin

Key Notes

  • Local Deletion:
  • -d (lowercase) checks if the branch is merged (safe).
  • -D (uppercase) forces deletion (even if unmerged).
  • Remote Deletion:
  • Requires push access to the repository.
  • Does not delete the branch from other collaborators’ machines (they must run git fetch --prune).
  • Current Branch: You can’t delete the branch you’re currently on. Switch first:
  git checkout main    # Switch to another branch (e.g., main)
  git branch -d old-branch

Example Workflow

Delete the dev/experiment branch locally and remotely:

# Delete locally
git branch -d dev/experiment

# Delete remotely
git push origin --delete dev/experiment

# Clean up local references
git fetch --prune

By following these steps, you can safely remove branches from your local and remote repositories!

Leave a Reply

Your email address will not be published. Required fields are marked *