How to Delete a Git Branch Locally and Remotely: A Guide

Git branches are a powerful feature that allows developers to work on different features or bug fixes simultaneously. However, once a branch has served its purpose, it’s a good practice to delete it to keep your repository clean and organised. In this guide, we’ll walk you through the process of deleting a Git branch both locally and remotely, complete with examples. Please note that this tutorial will work for any git systems, example like Github, Gitlab, BitBucket, ects.

Deleting a Local Git Branch

Step 1: List Your Local Branches

Begin by listing all your local branches. Open your terminal or command prompt and use the following command:

git branch

This command will display list of all your local branches, with the active branch marked with an asterisk.

Step 2: Switch to a Different Branch

If you’re on the branch you want to delete, switch to a different branch first. You can switch to another branch using the checkout command:

git checkout <branch_name>

Replace <branch_name> with the name of the branch you want to switch to.

Step 3: Delete the Branch Locally

Now that you’re on a different branch, you can safely delete the branch you no longer need. Use the following command to delete the branch locally:

git branch -d <branch_name>

If the branch has unmerged changes, Git will prevent you from deleting it with -d. In that case, use -D to force the deletion:

git branch -D <branch_name>

Step 4: Confirm Deletion

After executing the delete command, Git will confirm the deletion of the branch. If successful, you’ll see a message like this:

Deleted branch <branch_name> (was <commit_hash>).

Deleting a Remote Git Branch

Step 1: List Your Remote Branches

To delete a branch from remote repository, you first need to know the remote branches. Use the following command to list remote branches:

git branch -r

This command will display a list of remote branches. Note the name of the branch you want to delete.

Step 2: Delete the Remote Branch

Now that you know the name of remote branch you want to delete, use the push command with the --delete or -d option to delete it:

git push origin --delete <remote_branch_name>

Replace <remote_branch_name> with the name of the remote branch you want to delete.

Step 3: Confirm Deletion

After executing the delete command, Git will confirm the deletion of the remote branch. If successful, you’ll see a message like this:

To https://github.com/your-username/your-repository.git
 - [deleted]         <remote_branch_name>

Conclusion

Knowing how to delete Git branches both locally and remotely is an essential skill for maintaining clean and organized Git repository. By following the steps outlined in this guide, you can confidently manage your branches and keep your project streamlined. Remember to use caution when deleting branches, especially remote ones, as that action cannot be easily undone. Happy coding!

Find more tutorials on Git.