Tips for working with Git branches

If you work using pull requests, you're probably branching and switching branches a lot. Here are some tips that I've collected while working with Git on a day-to-day basis.

Branching off any branch

This is the first one in the "you don't have to check out your local master in order to do things" series.
Basically, when you want to create a new branch off another branch:

$ git checkout -b new-feature other-feature

Update your branch to latest master

You're working on a feature branch and you want to update it to latest master (you do this a lot if you use GitHub and your master branch is protected):

$ git merge origin/master
If you care about the very latest master, then fetch before merging:
$ git fetch
$ git merge origin/master

Going back to the previous branch

You checked out a branch, tested some stuff, now you want to go back to the branch you were a few minutes ago:

$ git checkout -
Of course, it works when you want to merge the branch you just left:
$ git merge -

What branch was I working on?

You checked out a few branches to work on your pull requests, also to review coworkers' code and provide your insightful feedback. You now want to pick up where you left off with some past work. What was that branch named?

$ git branch --sort=-committerdate | head

Push with a different name

You start working on a feature and you name the branch using what you know early on. As you progress, you realize the branch name no longer reflects the work you're about to push.

$ git push -u origin local-name-i-dont-like:remote-name-i-like
You probably want to rename your local branch too, but it's nice to know this one.

Deleting branches

To delete a local branch you no longer need:

$ git branch -d old-branch
Remember, your local branch is probably tracking a remote branch. The above command will not delete the branch in the remote. In order to do that, you need to "push nothing":
$ git push origin :old-branch
If you want to delete all your local branches that were merged to master:
$ git branch --merged | grep -v "\*" | xargs -n 1 git branch -d

Have any cool tips? Let me know!