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):
If you care about the very latest master, then fetch before merging:
$ git merge origin/master
$ 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:
Of course, it works when you want to merge the branch you just left:
$ git checkout -
$ 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.
You probably want to rename your local branch too, but it's nice to know this one.
$ git push -u origin local-name-i-dont-like:remote-name-i-like
To delete a local branch you no longer need:
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 branch -d old-branch
If you want to delete all your local branches that were merged to master:
$ git push origin :old-branch
$ git branch --merged | grep -v "\*" | xargs -n 1 git branch -d
Have any cool tips? Let me know!