18

This answer tells how to checkout to the previous branch, and helpfully explains @{-1}: https://stackoverflow.com/a/7207542/3150057

The previous branch is important if I stashed some code before changing branch, and am now thinking about working on the stash.

Is there a way to quickly see the name of the previous branch without searching git reflog show for the latest checkout: moving from foo to bar entry?


More info:

This is a solution to my forgetfulness of my previous working context, which usually happens after coming back from lunch.

git rev-parse @{-1} shows the HEAD commit of the branch that would be checked-out by git checkout - but not the branch name.

git branch --contains @{-1} will list every branch with that commit.

Listing the branch(es) with that commit as HEAD would be helpful, as it could help remind me of my previous working context, but I'm not sure how to do that.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Henry Blyth
  • 1,700
  • 1
  • 15
  • 23

2 Answers2

16

If you only want the name, you can use:

git rev-parse --symbolic-full-name --abbrev-ref=loose @{-1}

So for example:

$ git checkout mybranch
$ git checkout master
$ git rev-parse --symbolic-full-name --abbrev-ref=loose @{-1}
> mybranch

It is preferable to the accepted answer because it does not show "heads" in the name, so it can be chained with other git commands.

Warning

Previous answer was using

git name-rev $(git rev-parse @{-1}) --name-only

which only works if branches have different commits. Otherwise it might return the wrong branch

Gabriel Furstenheim
  • 2,969
  • 30
  • 27
12

Maybe this is what you want:

git describe --all $(git rev-parse @{-1})

From the git-describe man page:

--all

Instead of using only the annotated tags, use any ref found in refs/ namespace. This option enables matching any known branch, remote-tracking branch, or lightweight tag.

So for example, if I do this:

$ git checkout mybranch
$ git checkout master
$ git describe --all $(git rev-parse @{-1})

I see:

heads/mybranch
larsks
  • 277,717
  • 41
  • 399
  • 399
  • 4
    That does it, thanks! I was able to use `git describe --all @{-1}` and got the same result. – Henry Blyth Nov 04 '16 at 15:18
  • Getting `fatal: Not a valid object name @{-1}` :( – Hlung Dec 01 '17 at 06:10
  • 1
    `@{-1}` refers to "the th branch/commit checked out before the current one". If you have only ever used a single branch (e.g., `master`), then there is no "previous branch" and you will get the error you describe. Try `git checkout -b testbranch` and then see to what `@{-1}` refers. – larsks Dec 01 '17 at 13:06