Kostas Kostas - 4 months ago 76
Git Question

How do I move forward and backward between commits in git?

I am doing a

git bisect
and after arriving to the problematic commit, I am now trying to get a step forward/backward to make sure I am in the right one.

I know of
to go backwards in history but is there another shortcut to get me forward (towards a specific commit in the future) like so:

A - B - C(HEAD) - D - E - F

I know that my target is F and I want to move from C to D.

NOTE: this is not a duplicate of Git: How to move back and forth between commits, my question is slightly different and is not answered there


I've experimented a bit and this seems to do the trick to navigate forwards:

git checkout $(git rev-list --topo-order HEAD..towards | tail -1)

where towards is a SHA1 of the commit or a tag.


  • the command inside $() means: get all the commits between current HEAD and towards commit (excluding HEAD), and sort them in the precedence order (like in git log by default -- instead of the chronological order which is weirdly the default for rev-list), and then take the last one (tail), i.e. the one we want to go to.
  • this is evaluated in the subshell, and passed to git checkout to perform a checkout.

You can define a function accessible as a parameter-expecting alias in your .profile file to navigate forward towards the particular commit:

# Go forward in Git commit hierarchy, towards particular commit 
# Usage:
#  gofwd v1.2.7
# Does nothing when the parameter is not specified.
gofwd() {
  git checkout $(git rev-list --topo-order HEAD.."$*" | tail -1)

# Go back in Git commit hierarchy
# Usage: 
#  goback
alias goback='git checkout HEAD~'