How do I delete a Git branch locally and remotely?
Deleting a Git Branch Locally
To delete a Git branch locally, you can use the following command:
git branch -d branch_name
Replace branch_name
with the name of the branch you want to delete.
Deleting a Git Branch Remotely
Deleting a Git branch from a remote repository involves two steps:
- Delete the branch locally using:
- Delete the branch from the remote repository using:
git branch -d branch_name
git push origin --delete branch_name
Again, replace branch_name
with the name of the branch.
Additional Questions
How can I delete a Git branch without checking it out?
To delete a Git branch without checking it out first, you can use:
git branch -d -r origin/branch_name
This deletes the remote branch without needing to switch to it locally.
What if I want to delete multiple Git branches at once?
You can delete multiple Git branches at once by specifying each branch name:
git branch -d branch1 branch2 branch3
This deletes branch1
, branch2
, and branch3
locally.
Is it possible to recover a deleted Git branch?
If you accidentally delete a Git branch, you may be able to recover it if it hasn't been garbage collected by Git yet. You can try:
git reflog
Find the commit associated with your deleted branch and recreate it using:
git checkout -b branch_name commit_hash