DEV Community

Srinivas Ramakrishna for ItsMyCode

Posted on • Originally published at itsmycode.com on

Git Delete local branch

ItsMyCode |

While working on a project, it always becomes tedious to manage git branches. We often create many feature branches on local and remote, and later it becomes difficult to manage the git branches. In this article, let’s take a look at how to delete local branch in Git.

Git Delete local branch

First, let us list out all the branches that we have in our local and remote using the *git branch * command.

List all Git branches

In order to list all the git branches, you can run the git branch command with the -a flag(all).

git branch -a
Enter fullscreen mode Exit fullscreen mode

Output

  develop
  master
  feature-1
  remotes/origin/develop
  remotes/origin/master
  remotes/origin/feature-1
Enter fullscreen mode Exit fullscreen mode

Git command to delete local branch

You can delete the local branch using the git branch command followed by the -d (delete) flag and provide the local branch name you need to delete.

Syntax

$ git branch -d <branch_name>
$ git branch -D <branch_name>
Enter fullscreen mode Exit fullscreen mode
  • The -d option is an alias for --delete. Using this flag can only delete the branch if it has already been fully merged to its upstream branch.
  • The -D option is an alias for --delete --force. It is a force deletion of a branch. Using this flag deletes the branch β€œ irrespective of its merged status.”
  • You will receive an error if you try to delete the currently selected branch.

Example delete local branch

You could use one of the below commands to delete your local branch.

$ git branch -d feature-1

$ git branch -D feature-1
Enter fullscreen mode Exit fullscreen mode

Output

Deleted branch feature-1 (was 0c3dae4).
Enter fullscreen mode Exit fullscreen mode

Git Delete Remote Branch

Deleting the remote branch is slightly different from deleting a local branch. You cannot use the git branch command to delete remote branches. Instead, we need to use the git push command with the β€” delete flag to delete a remote branch. Ensure to provide the remote branch name correctly.

If you are looking to delete the remote branch, you can use the below command.

git push origin --delete <branch> # Git version 1.7.0 or newer
git push origin -d <branch> # Shorter version (Git 1.7.0 or newer)
git push origin :<branch> # Git versions older than 1.7.0
Enter fullscreen mode Exit fullscreen mode

Example Delete remote branch in Git

$ git push origin --delete feature-1
Enter fullscreen mode Exit fullscreen mode

Output

The post Git Delete local branch appeared first on ItsMyCode.

Top comments (0)