Delete a local Git branch using terminal

Sometimes we have a situation where the deletion of the local branch is needed. So in this article, we will see

  1. Delete a Git branch that exists in a local using terminal.
  2. Forcefully delete a local Git branch using terminal

It is very often with repositories that they have a master branch and based on it developers create other child branches to develop or fix different features.

Once work with the child branch is completed, it’s recommended to delete the branch.

Deleting a local branch using terminal

In order to delete a local Git branch, first, we need to switch to another branch say suppose master branch. As Git will prevent deletion of the branch that we are currently working on, so we must make sure to checkout to another branch before deleting an actual branch.


Command to switch to master branch

git checkout master

Deleting local Git branch

After checking into another branch, we can delete the useless branch, with the below command by specifying the branch name.

git branch -d branchName

The -d option will delete the specified branch and is also an alias for --delete.

Note: Replace branchName with an actual branch name that needs to be deleted.

Example
git branch -d refactor/media

Deleting local Git branch forcefully

In some cases, Git refuses to delete a local branch. When the branch contains commits that aren’t still pushed to a remote repository or not yet merged into the other local branch. This protects us from unintentionally losing committed data.

If there is still a need to delete such a branch, we can do it with the -D option

git branch -D branchName

The -D option will delete the specified branch regardless of its merge status and is also an alias for --delete --force.

Note: Replace branchName with an actual branch name that needs to be deleted.

Example
git branch -D feature/authentication

Hope you like this!

Keep helping and happy 😄 coding

Avatar

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳

Next
Previous