0

Say if I checked out a previous version of a repo. Let's assume each commit is represented by a number for simplicity, illustrated below. How can I check out the version after the one HEAD is pointing at? I know I can get to the previous commit by

git checkout HEAD~1

but how can I get to the latter commit, in this case, commit number 4, without knowing its SHA-1 value?

1    2     3        4         5
          HEAD
Zoe
  • 27,060
  • 21
  • 118
  • 148
Zhengquan Bai
  • 1,057
  • 3
  • 14
  • 31
  • Multiple commits could have 3 as their parent. What would you like to happen in this case? – Tom Apr 26 '17 at 10:20
  • You mentioned that multiple commits could possibly share the same commit as their parent. I can only think of this scenario when there're several branches. What if I confine this discussion to the current branch I'm working on? – Zhengquan Bai Apr 26 '17 at 10:27
  • 1
    The answer by Jan Kruger is, I believe, as good as you'll get. As he notes, there are several assumptions built in and behavior may be unexpected if any of those assumptions doesn't hold. Your stated "assume current branch" is unfortunately not precise in git's terms, because the relationship between a commit and a branch isn't that concrete. (Most notably, once you've checked out commit `3`, you aren't on *any* branch.) – Mark Adelsberger Apr 26 '17 at 14:00

1 Answers1

2

This is not so easy because Git doesn't have any way to reference "future" commits (when 3 is checked out, there is no readily available reference to 4). However, if we bake a lot of assumptions into it, we can create a shell monster to do this (abbreviations avoided for clarity):

git checkout $(git rev-list --first-parent --reverse HEAD..master | head -1)

Please note that this will only work if your currently checked out commit is not part of a merge (reachable only via the second parent of a merge commit). We could make a bigger monster to automatically find the right merge commit, too, but then it would begin to take on the size of a dedicated tool...

Jan Krüger
  • 17,870
  • 3
  • 59
  • 51
  • 1
    Would only add, because OP put this in terms of "current branch"... I noted above that talking about "current branch" is at best imprecise here, but let's take it to mean OP wants to follow a particular branch. Then that branch name (which might or might not be `master`) would go after the `HEAD..`. – Mark Adelsberger Apr 26 '17 at 14:03