Git

Git Delete Remote Branch

When working with Git, you will interact with branches more often. A Git branch is a separate sub-repository that contains its changes, features, and modifications without affecting the main repository. This allows developers to add experimental features without corrupting the main source code.

You can then make the changes and, once satisfied, merge them with the main repository without worrying about breaking changes.

However, you may encounter a scenario where you need to delete a remote branch for a specific repository. Let us explore how we can accomplish this in this tutorial.

Git Delete Remote Branch

Git allows you to delete a remote branch using the Git push command followed by the delete option.

The command syntax is provided below:

git push remote_repo --delete target_branch

The –delete option tells Git that you wish the convert the push operation into a delete.

Another syntax passes the target branch, as shown below:

git push remote_repo :target_branch

For example, to delete a branch called temp_branch from a remote repository, we can run a command, as shown below:

git push origin --delete temp_branch

In our case, we specify the remote branch name as an origin. This will take the specified repository referenced by the name origin and remove the specified branch.

Git Delete Local Branch

In some cases, you may also need to delete a local branch. Luckily a local branch is stored on the local machine, and removing it does not affect the remote branch.

Therefore, to remove a local branch, we can use the Git branch command followed by the -d option. This tells Git to drop the branch with the specified name.

The command syntax is shown below:

$ git branch -d target_branch

The command should remove the branch within the specified repository.

If you have unmerged changes in the target branch, Git will show an error and fail to drop the branch. To discard the changes and drop the branch, use the -f flag as shown in the command below:

$ git branch -fd target_branch

Use the -f option carefully, as it will completely discard all the unmerged changes. This action is irreversible.

You can substitute the -f flag with -D, which performs a similar action.

Conclusion

This short article taught you how to remove a remote and local branch from a specific Git repository. Keep in mind that local and remote branches are not related. Hence, removing one does not automatically reflect on the other repository. You need to remove each branch manually.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list