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:
git switch - will take me to branch develop (same as git switch @{-1})git switch @{-1} will take me to branch developgit switch @{-2} will take me to branch featuregit switch @{-3} will take me to branch developgit switch @{-4} will take me to branch mainAs 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?
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)
git reflog | awk '/checkout: moving from/ && !seen[$NF]++ {print $NF}'
git reflog | awk … | sed -n "${n}p"
or
git reflog | awk … | awk "NR==${n}"
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)
git sn 5 # go to 5th last branch
git sn # go to previous branch