Robin Bastiaan
Robin Bastiaan

Reputation: 702

How to switch to the Nth previous unique branch in Git?

Lets say I have 3 branches in my repository: main, develop and feature. Now, suppose I have switched my working branch in the following order: from main, to develop, to feature, back to develop, and to feature again.

From this position I would like to go back to my main branch without having to write main so that in theory I can forget the name of my branch. The switch command can come a long way with the @{-N} notation to refer to the N-th last branch/commit, like so:

As you can see, this lists all your previous working branches. However, since I will be switching between develop and feature multiple times before wanting to go back to main, I would have to remember the precise amount of times I have switched between develop and feature since I left main. I would like to be able to refer to a previous unique branch, such that something like git switch @{-2} --unique would take me to main, but that option does not exist for the git switch command at least.

I have found a handy trick to list your most recently-used branches using Git, and that will list your branches uniquely. Maybe it is possible to take that idea to create a way to switch to the Nth previous unique branch?

Upvotes: 2

Views: 95

Answers (1)

knittl
knittl

Reputation: 265717

The simplest is still to use git switch main. But if you really want to …

Should be simple enough (although will start to fail if output of git reflog changes – it's not intended to be parsed)

Get unique branch names from reflog:

git reflog | awk '/checkout: moving from/ && !seen[$NF]++ {print $NF}'

Select n'th entry

git reflog | awk … | sed -n "${n}p"

or

git reflog | awk … | awk "NR==${n}"

Make it an alias (sn – "switch n")

git config --global alias.sn '!f() {
  branch="$(git reflog | awk '\''/checkout: moving from/ && !seen[$NF]++ {print $NF}'\'' | awk "NR==${1:-1}")";
  git switch "$branch";
}; f'

(n will default to 1 – the most recent branch)

Use it

git sn 5 # go to 5th last branch
git sn   # go to previous branch

Upvotes: 1

Related Questions