We can checkout the last branch using git checkout -
, but is there a way to just find out what was last branch and not check it out?
EDIT: I already found that I could use:
git reflog | grep -i "checkout: moving"|head -1|cut -d' ' -f6
But I wanted to know if there is a direct simpler command. I am updating the question to reflect this need. Sorry about not being clear enough
Use the git switch - (Or git checkout - ) to switch to the previous branch you were working with. This is pretty similar to the cd - command, which is used to switch to the previous directory.
The git checkout command lets you navigate between the branches created by git branch . Checking out a branch updates the files in the working directory to match the version stored in that branch, and it tells Git to record all new commits on that branch.
The "checkout" command can switch the currently active branch - but it can also be used to restore files. The most common use case for "checkout" is when you want to switch to a different branch, making it the new HEAD branch.
The HEAD points out the last commit in the current checkout branch. It is like a pointer to any reference. The HEAD can be understood as the "current branch." When you switch branches with 'checkout,' the HEAD is transferred to the new branch.
Your sample output (as produced by git reflog | ...
) makes it sufficiently clear.
The git rev-parse
command can be combined with the reference lookup syntax to do this in one go:
$ git rev-parse --symbolic-full-name @{-1}
refs/heads/stash-exp
$ git rev-parse --abbrev-ref @{-1}
stash-exp
Note that the gitrevisions
documentation describes the @{-N}
syntax. Note as well that if there is no N'th previous branch, rev-parse
silently prints nothing at all:
$ git rev-parse --abbrev-ref @{-2} && echo ok || echo fail
master
ok
$ git rev-parse --abbrev-ref @{-3} && echo ok || echo fail
ok
And, of course, in most places where you might need the name, you can just use the @{-1}
syntax directly.
git reflog
is what you want to use. In this, you'll find:
What you've checked out is important here; the reflog will use a format denoted with "checkout" and specify "moving from A to B" when looking at specific branches.
A simple grep for "checkout: moving" will give you a list of the branches you've visited; the last one is at the top.
Full command for completeness:
git reflog | grep -i "checkout: moving"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With