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 branchdevelop
(same asgit switch @{-1}
)git switch @{-1}
will take me to branchdevelop
git switch @{-2}
will take me to branchfeature
git switch @{-3}
will take me to branchdevelop
git switch @{-4}
will take me to branchmain
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?
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:
Select n'th entry
or
Make it an alias (
sn
– "switch n")(n will default to 1 – the most recent branch)
Use it