-2

How can I get a previous branch/commit using Git plumbing commands or status files?

Edit: The question is - how can I get this information (the previous branch or commit) without performing an actual checkout? This is needed for a tool which works on top of Git, not for a regular Git scenario.

Dmitry Petrov
  • 1,490
  • 1
  • 19
  • 34

1 Answers1

1

By taking a look in the code:

if (!strcmp(arg, "-"))
    arg = "@{-1}";

The way to access the previously checked out branches is documented in revisions doc on @{-n}

Now, to resolve the branch name behind @{-n}, the solution is git check-ref-format --branch:

With the --branch option, it expands the “previous branch syntax” @{-n}. For example, @{-1} is a way to refer the last branch you were on. This option should be used by porcelains to accept this syntax anywhere a branch name is expected, so they can act as if you typed the branch name.

$ git check-ref-format --branch @{-1}
my_branch
$ git check-ref-format --branch @{-2}
master

There is also the git rev-parse --symbolic-full-name solution:

$ git rev-parse --symbolic-full-name @{-1}
refs/heads/my_branch
$ git rev-parse --symbolic-full-name @{-2}
refs/heads/master
zigarn
  • 10,892
  • 2
  • 31
  • 45
  • This is pretty much the same as `git checkout -`. The question is - how can I get this information (the previous branch) without performing an actual checkout? – Dmitry Petrov Nov 05 '17 at 04:23
  • `git check-ref-format --branch @{-1}` is what I was looking for. Thank you, @zigarn! – Dmitry Petrov Nov 06 '17 at 18:29