How do I delete a Git branch locally and remotely?
How to Delete a Git Branch Locally and Remotely
Deleting Git branches is a common task when you want to clean up branches that are no longer needed. Here’s a step-by-step guide on how to delete a Git branch both locally and remotely.
Deleting a Local Git Branch
To delete a local branch, you can use the git branch
command with the -d
or -D
option.
Using '-d' (Safe Delete)
The -d
option deletes the branch only if it has been fully merged into its upstream branch. This is a safe way to delete branches to avoid losing work.
Command:
git branch -d branch_name
Example:
git branch -d feature-branch
Using '-D' (Force Delete)
The -D
option force deletes the branch, even if it has not been merged. Use this with caution as it can lead to data loss.
Command:
git branch -D branch_name
Example:
git branch -D feature-branch
Deleting a Remote Git Branch
To delete a remote branch, you use the git push
command with the --delete
option.
Command:
git push remote_name --delete branch_name
Example:
git push origin --delete feature-branch
Alternatively, you can use the more explicit form with a colon (:
) syntax:
Command:
git push remote_name :branch_name
Example:
git push origin :feature-branch
Summary
Delete a Local Branch
-
Safe Delete (only if fully merged):
git branch -d branch_name
-
Force Delete (even if not merged):
git branch -D branch_name
Delete a Remote Branch
-
Using
--delete
option:git push remote_name --delete branch_name
-
Using colon (
:
) syntax:git push remote_name :branch_name
Example Workflow
Suppose you have a branch named feature-branch
that you want to delete both locally and remotely.
-
Delete the local branch:
git branch -d feature-branch
If the branch is not fully merged and you still want to delete it:
git branch -D feature-branch
-
Delete the remote branch:
git push origin --delete feature-branch
Alternatively:
git push origin :feature-branch
By following these steps, you can effectively clean up branches in your Git repository.
For more detailed tutorials on Git and other coding practices, consider checking out Grokking the Coding Interview from DesignGurus.io and TechGrind.io, which offers comprehensive courses on essential coding and interview techniques.
GET YOUR FREE
Coding Questions Catalog