Introduction

Git is a project-tracking application that creates a main project thread that can be branched.

Git branches are used to develop changes and updates without affecting the core project. Files in a branch may need to be deleted if they become corrupted or obsolete after merging branches.

This guide shows you how to delete remote and local branches in Git.

tutorial on deleting remote and local git branch

Prerequisites

  • A Git project
  • A user with privileges to delete files from the project

What are Git Branches?

Git branch is a copy of the project from a specific point in time. Once changes have been made and approved, you can commit the branch changes to the main project. In some cases, it may be necessary to undo Git commits.


Note: A user can check out a branch from a previous version, make changes, then publish the update. Changes are not permanent until they are committed. Git tracks revisions through the life span of a project.


Git can span multiple systems. A central server keeps the main project files. Users can check out a project, make changes on their local system, then publish the changes back to the server.

      • The files and branches on the main server are remote branches.
      • The files and branches on a user’s system are called local branches.

Deleting a Remote Branch

remote branch is located on a different system; usually, a server accessed by developers. Deleting a remote branch removes it for all users.

Delete a remote Git branch by entering the following command:

git push remote_project --delete branch_name

As an alternative, use the following command to delete a remote branch:

git push remote_project :branch_name

In some cases, this may generate an error that indicates that the branch has already been deleted.

Git branch deletion error example.

Refresh the branch list before trying to delete the remote branch again:

git fetch -p

Deleting a Local Branch

local branch is stored on the local system. Deleting a local branch does not affect a remote branch. Check out a local GIt branch that you DO NOT want to delete:

git checkout main_branch

Use the following command to delete a local branch:

git branch –d branch_name

The system confirms the name of the deleted branch.

Confirmation and name of the deleted local Git branch.

The –d option only works on branches that have been pushed and merged with the remote branch. To force deletion of a local branch that has not been pushed or merged yet, use the –D option:

git branch –D branch_name

Conclusion

You now know how to delete local and remote Git branches. Learning to manage Git branches effectively is vital for developer collaboration when working on demanding projects.


Next you should also read