Nowadays, it's hard to imagine product development without using Git branches to deliver a part of the functionality.
A branch is an independent line of development used in order not to interfere with the main line, which can even be used in production.
There is no limit to the number of branches you can have, but it is a good practice to delete the unused branches, both locally and on Github.
Today we'll learn how to delete local and remote Git branches, and also how to undo the delete operation if needed.
If the branch has not been pushed to the remote, it can be easily deleted with the following command:
git branch -d <name>
Let's create a new branch feat/feature and delete it:
However, there are a few cases where Git refuses to delete your local branch:
If there was no protection, you could have accidentally deleted the branch and lost all your data.
But if you are really sure that you want the unmerged branch to be deleted anyway, you can use the following command:
git branch -D <name>
If the branch has been pushed to remote, you can delete it with the following command:
git push origin --delete <name>
Note that the branch is not deleted locally.
If you have accidentally deleted a local branch with some important changes, you can restore the changes with a combination of the following commands:
git checkout -b <name> <hash>
Create a branch and delete it:
Use reflog to see what has been done recently:
And create a new branch with the deleted commit:
In this article, we learned how to delete local and remote Git branches and also how to undo the deletion if it happened accidentally.
Be sure to play around with the commands to learn and understand them better.