Git quick tips #2: Working with many branches

- git productivity tips

I somehow often end up working on a few branches in parallel and some things make my life easier:

  1. git switch -: Like the cd command git switch and git checkout take a - argument which takes you back to the previously checked out branch.
    $ git branch
    * citizen428/long-branch-name
    $ git switch main
    Switched to branch 'main'
    Your branch is up to date with 'origin/main'.
    $ git switch -
    Switched to branch 'citizen428/long-branch-name'
    Your branch is up to date with 'origin/citizen428/long-branch-name'.
    I actually have checkout aliased to co and switch to sw (as well as git itself to g) but I didn’t want to confuse readers with those.
  2. git show branch:file_name: Especially during some of my recent work I often had several branches that modified the same files. A quick way to see a file from another branch without having to check it out is git show, e.g. git show main:app/models/user.rb.
  3. git-rerere: Short for “reuse recorded resolution”. Particularly useful for long-running branches (which ideally we shouldn’t have but ideals don’t tend to survive contact with reality). The process is automatic and doesn’t generally require manual intervention, just make sure it’s enabled in your git configuration, e.g. git config --global rerere.enabled true. The git docs have a very nice explanation.
  4. git stash branch: I sometimes start working in the wrong checkout and a quick and easy way to correct this is the following:
    $ git stash # stash current changes
    $ git stash branch <branch name>
    This will directly create a new branch from the stash instead of having to first create it and then using git stash pop. Keep in mind that the currently active branch will be used as the base, so unless you’re already on main you may want to check that out first.
  5. git autocorrect: Not directly related to branch management but it can be useful for the commands I use rarely and have not aliased. You can configure it like this git config --global help.autocorrect 10, where the integer is a value in 10th of a second, so the above will wait for 1 second before running the autocorrected command: autocorrect in action