P.Brian.Mackey P.Brian.Mackey - 1 year ago 47
Git Question

What is the difference between all these similar delete commands?

I've seen several ways to delete branches:

git push origin --delete --force rc

git branch -D rc

git branch -dr origin/rc

In a blog I saw a guy do yet another kind of delete:

Delete the old-name remote branch and push the new-name local branch.

git push origin :old-name new-name

Reset the upstream branch for the new-name local branch.

git push origin -u new-name

For the blog example, it looks like he is doing the same thing twice. Didn't he just push new-name to remote? I don't see the need for the second command here.

I've seen a popular way to do it on stackoverflow. I tried the most upvoted answer:

git branch -d branch_name
git push origin --delete <branchName>

I find that I need to run both of these commands (I use -D in place of -d) to reliably delete both local and remote.

I want a reliable way to delete both local and remote branches for a branch named rc. Do I need to run two seperate commands? What is the difference between all these commands?

Answer Source

Yes, you must run two commands, one to delete local branch and one for remote, but you could easily make an alias if you want to do this often.

git push origin --delete --force rc

Deletes remote branch

git branch -D rc

Deletes local branch, regardless of whether it's merged

git branch -dr origin/rc

Deletes your local tracking branch of the remote. This automatically happens with the first command. This command is the least common, and is only needed if you deleted the remote branch from a different machine, and now this local repository just needs to prune the obsolete tracking branch.

The only difference between -d and -D is to delete local branches that are not merged. -D tells git you don't care if it's not been merged. This only applies to local branches.

The usage for push ref spec is

git push <remote> <local name>:<remote name>

So this is clean and easy for me to remember because if you leave local name blank, then it pushes nothing to that remote name effectively deleting it.

git push origin :oldBranch

As for the blog

git push origin :old-name new-name

This deletes the old branch and pushes the same branch up again under a new name. In effect, he's renamed the branch, but it's not tracked as such, so you need:

git push origin -u new-name

Even though it's the same branch, it is technically tracked as a different remote branch, so the -u flag sets to track it. If you run these back to back, then the second push won't actually push anything, just enable tracking.