Deleting Git Branches Locally And Remotely

September 5, 2020

When working with Git, we can create branches to work on new features and keep the code separate from the rest of the project.

It is common to have a "main" master branch, and once we are happy with the changes made on the branch, we can then merge them in with the master.

If the branch code does not work out and we want to remove it, or, after merging we can delete the branch. Let's begin by removing the branch locally.

  1. To delete a branch locally the first thing to do is to make sure we are not currently working on it. We can change branches, i.e back to the master like this:

    git checkout master
    
  2. Then to delete the branch, we have 2 options, depending if you have pushed and merged with the remote branch:

    // -d (delete) to remove only if you have pushed and merged
    // it with your remote branch
    git branch -d branch_name
    
    // -D (delete/force) to remove even if you have not pushed and merged
    // it with your remote branch
    git branch -D branch_name
    
  3. We have now successfully removed our local branch. We now need to remove it remotely too using the following command:

    git push <remote> --delete <branch_name>
    
    // which looks something like this with your variables:
    git push origin --delete new_checkout_flow
    
  4. Enter your password, and all done! You can check GitHub and the branch should now be removed.