How to delete a Git branch locally and remotely?

To delete a Git branch both locally and remotely, you need to use the following commands.


1. Delete a Local Git Branch

To delete a branch locally, you use the git branch -d or git branch -D command.

Command to delete a local branch safely (if it’s already merged):

git branch -d <branch-name>
  • Effect: Deletes the local branch only if it has already been merged into the current branch or the base branch (e.g., main or master).

Command to force delete a local branch (even if it’s not merged):

git branch -D <branch-name>
  • Effect: Deletes the local branch even if it hasn’t been merged. Use this with caution as you may lose unmerged changes.

Example:


git branch -d feature/old-feature

or if you want to force delete it:

git branch -D feature/old-feature

2. Delete a Remote Git Branch

To delete a branch from the remote repository, use the git push command with the --delete option.

Command:

git push origin --delete <branch-name>
  • Effect: Deletes the specified branch from the remote repository (e.g., origin).

Example:

git push origin --delete feature/old-feature

3. Delete a Remote Git Tracking Branch Locally

If you’ve deleted a remote branch but the tracking branch still exists locally, you can clean up the reference with the following command:

Command:

git fetch -p
  • Effect: Removes references to remote branches that no longer exist.

Example:

After deleting a branch remotely (git push origin --delete), clean up the reference:

git fetch -p

4. Verify Deletion

After deleting the branch, you can verify the branch is deleted:

Verify local branch deletion:

git branch

This will list the remaining local branches.

Verify remote branch deletion:

git branch -r

This will list the remaining remote-tracking branches.


Full Example Workflow

  1. Delete Local Branch (if already merged):
    git branch -d feature/old-feature
  2. Delete Remote Branch:
    git push origin --delete feature/old-feature
  3. Clean Up Remote References Locally:
    git fetch -p

Summary of Commands

ActionCommand
Delete a local branch (merged)git branch -d <branch-name>
Force delete a local branch (unmerged)git branch -D <branch-name>
Delete a remote branchgit push origin --delete <branch-name>
Clean up remote references locallygit fetch -p

No images available.