When work gets hectic (or sporadic), I often find myself forgetting what I had named various branches or what I had been working on. To this end, I crafted a new git alias, lb, which stands for “last branches”.

git lb will respond with something like this (with a splash of color):

  31 minutes ago: fun-branch
  2 days ago: remove-things
  3 days ago: staging
  6 days ago: remove-bugs
  7 days ago: add-bugs
  7 days ago: master
  2 days ago: dev
  3 weeks ago: enhance_something
  3 weeks ago: hotfix-1
  4 weeks ago: undo-mess

which is an ordered list of the last 10 branches you have checked out and the time you were most recently on them.

To use this alias, add the following to your ~/.gitconfig:

    lb = !git reflog show --pretty=format:'%gs ~ %gd' --date=relative | grep 'checkout:' | grep -oE '[^ ]+ ~ .*' | awk -F~ '!seen[$1]++' | head -n 10 | awk -F' ~ HEAD@{' '{printf(\"  \\033[33m%s: \\033[37m %s\\033[0m\\n\", substr($2, 1, length($2)-1), $1)}'

This builds on the technique in:

  • https://stackoverflow.com/questions/40291034/how-to-find-the-last-branch-checked-out-in-git

Quickly, here are the pipeline steps broken down:

  • git reflog show --pretty=format:'%gs ~ %gd' --date=relative: Gives us the raw data we need. Try it yourself. The rest is formatting.
  • grep 'checkout:': Filters out all the irrelevant lines that reflog is giving us.
  • grep -oE '[^ ]+ ~ .*': Keeps only (-o) the part of the line that we care about.
  • awk -F~ '!seen[$1]++': Split fields (-F) on ~. Increment a counter array for each item. Skip the line if the part before the ~ ($1) was already found. This is the part that gives us the “don’t show branches more than once”.
  • head -n 10: Keep only the most recent 10 branches.
  • awk -F' ~ HEAD@{' '{printf(\" \\033[33m%s: \\033[37m %s\\033[0m\\n\", substr($2, 1, length($2)-1), $1)}': Reformat to give some pretty ANSI colors and a cleaner output.