Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the output of git branch by most recent checkout

Tags:

git

branch

I have a lot of local branches. Running git branch lists them and they overflow the page. I often want to toggle between the currently checked out branch and the branch I was working on last, or possibly one before the last. The process is to scan the list of 20-30 local branches by eye or possibly command+f if I'm lucky enough to remember a keyword (or ticket number).

Instead I'd like to say git branch and have it display branches by checkout order. The same way you seem many items listed in many programs ordered by most recent activity. This seems like an obvious default choice for order criterion and I'm surprised it isn't git's default.

edit:

i revised my question to ask only about a sort by checkout. i'm unable to find a sorting predicate that will filter the output of git branch by the date of each branches most recent checkout.

like image 789
Alex Bollbach Avatar asked Dec 21 '17 15:12

Alex Bollbach


1 Answers

List Branches in the order they were checked out (not in last commit order):

git log -g --grep-reflog "checkout:" --format="%gs" | cat -n | sed -E "s/^\s+([0-9]+).*from (.*) to .*/\1 \2/g" | tac

You can then check one of them out with

git checkout @{-nnn}

where nnn is the number displayed before the branch name. To toggle between the current and previous branch, simply use

git checkout -

You can combine above command to new git command like this:

git config --global alias.lb '!git log -g --grep-reflog "checkout:" --format="%gs" | cat -n | sed -E "s/^\s+([0-9]+).*from (.*) to .*/\1 \2/g" | tac; read -p "Aussuchen: " i; git checkout @{-$i}'

to use

git lb

to display the last used branches and select one of them.

like image 81
Marcus Avatar answered Oct 22 '22 17:10

Marcus