How To Delete Local Branch In Git?

Git provides the git branch -d command in order to delete the local branch in a git repository. This command accepts the branch name as a parameter which will be deleted. Keep in mind that this command only deletes the local branch and can not be used to delete the remote Git branch.

List Local Branches

Before deleting a branch we can list currently existing branches with the following git branch command. The currently active branch is expressed with the * which is master in the following example.

$ git branch
List Local Branches

Delete Local Branch

The default way to delete a local branch in git is using the git branch -d . The -d option is used for delete operation. The long form of the -d option is --delete . The branch which will be deleted is added as a parameter like below. In the following example, we delete the branch named testing .

$ git branch -d testing

Alternatively, the log form delete option “–delete” can be used like below.

$ git branch --delete testing

Delete Local Branch Forcefully

If the branch you want to delete contains commits that haven’t been merged to the local branches or pushed to the remote repository the -d or --delete option does not works. The local branch removal or delete operation can be forced with the -D option.

$ git branch -D testing

“error: Cannot delete branch ‘testing’ checked out at”

When we try to delete the currently active branch we get the “error: Cannot delete branch ‘testing’ checked out at” error. This error cause is the branch we want to delete locally is currently active. In order to solve this error and delete the local branch, we should switch to another branch.

$ git branch -d testing
error: Cannot delete branch 'testing' checked out at

So we use the git switch command by providing the branch name we want to switch. In this case, we use the master.

$ git switch master

Now we can delete the local branch “testing” without a problem.

“error: Cannot delete branch ‘testing’ checked out at”

Leave a Comment