Git: delete branch

When working with Git, it’s common for projects to contain multiple branches. Over time, these branches may become irrelevant and need deleted. Other times, they change purpose and its necessary to rename the branch.

In this guide, we’ll show you the step by step instructions for deleting Git branches via the command line on a Linux system. We’ll show the process for deleting local branches as well as remote branches in the sections below.

In this tutorial you will learn:

  • How to delete local and remote Git branches

Deleting a local and remote Git branch

Deleting a local and remote Git branch
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software Git
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Delete Git Branch

To get started deleting a branch locally, the HEAD needs to be pointed at a branch you wish not to delete. For example, let’s say we want to delete branch linuxconfig. First, we should checkout a different branch – master is usually a safe bet.



$ git checkout master

Now we can use the following command to delete the branch.

$ git branch -d linuxconfig

The -d option will only work if the local and remote branches are currently in sync. Alternatively, you could use the -D option to force the deletion no matter what.

Now, we can delete the branch remotely with the following syntax.

$ git push <remote> --delete <branch>

If working with branch linuxconfig like above, it’d look like this:

$ git push origin --delete linuxconfig

Afterwards, you should refresh your branch list with the following command:

$ git fetch -p

The -p option stands for prune and will get rid of any references to lingering branches that have been deleted.

Conclusion

In this guide, we saw the steps for deleting a local and remote branch in Git. The process is simple and can be used any time that a branch in your project becomes irrelevant and isn’t needed for merging with other branches.