In this blog post I will show you two tricks how to easily switch between a branch back and forth and how to get the last checked out branches.
Switch between branches
Imagine you are on branch feature-1
and you want to switch to branch main
to do some work there. After you are done with your work on main
you want to switch back to feature-1
. Without knowing the exact branch name you can easily use:
git checkout -
git switch - # since git 2.23
Getting the last 5 checked out branches
If you want to see the last 5 branches you checked out you can use the following command:
git reflog | grep -o 'checkout: moving from [^ ]* to [^ ]*' | awk '{print $NF}' | awk '!seen[$0]++' | head -n 5
This works with the git bash and OS' like Linux and MacOS. The idea is to use the reflog
to get the history of the branches you checked out. The grep
command filters the output to only show the branches you checked out. The first awk
command extracts the branch names from the output. The second awk
command removes duplicates. The head
command limits the output to the last 5 branches. So if you want only the last 3 branches you checked out you can change the head -n 5
to head -n 3
.