Reputation: 7175
When moving between Git branches I sometimes forget the name of a branch I was recently on. How can I display a list of recently checked out branches/tags/commits in order of checkout?
Upvotes: 56
Views: 15274
Reputation: 70314
Here's a powershell script I cobbled together based on the other answers here:
function gsh() {
# git switch with history of recent branches
$branch = & git reflog | Select-String -Pattern "moving from (\S+) to (\S+)" | %{ $_.Matches.Groups[1].Value } | Invoke-Fzf -NoSort
if ($branch)
{
& git switch $branch
}
}
It makes use of the awesome fzf fuzzy finder to allow interactive selection of the branch to switch to - including fuzzy-filtering of the branches! See PSFzf for details on how to get the Invoke-Fzf
command.
Upvotes: 1
Reputation: 729
I have a similar one liner in my zshell , it takes an arg to specify how long the history should be, which defaults to 10.
alias bstack='f() { git reflog | grep checkout | cut -d " " -f 8 | uniq | head ${1} | cat -n };f'
for example, to list the last 3 branches
bstack -3
1 my-current-branch
2 my-previous-branch
3 my-third-most-recent-branch
I derived a couple useful shortcuts from this
alias bjmp='fn() { bstack ${1} | tail -1 | cut -f 2 | xargs git checkout }; fn'
allows me to specify from the numbers above which branch to check out
bjmp -3
will checkout "my-third-most-recent-branch"
alias b="bstack -1"
alias bpop="bjmp -2"
are also useful to see the current branch in a single keystroke (although this is not the easiest way to do this), and to just checkout the previous branch.
Upvotes: 5
Reputation: 7175
You can use Git's reflog
to show recent movements in order of checkout: git reflog
Here's a script you can download and use via git recent
from inside any Git repository: https://gist.github.com/jordan-brough/48e2803c0ffa6dc2e0bd
$ (master) git recent -n 5
1) master 4) deleted-branch
2) stable 5) improve-everything
3) fun
Choose a branch: 2
$ (stable) …
See the gist for more details/options.
Here's essentially what the script does to make the reflog output more usable:
$ git reflog | egrep -io "moving from ([^[:space:]]+)" | awk '{ print $3 }' | awk ' !x[$0]++' | egrep -v '^[a-f0-9]{40}$' | head -n5
master
stable
fix-stuff
some-cool-feature
feature/improve-everything
Upvotes: 87