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

Viewed 126924

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 HEAD^ 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

15 Answers

Traversing backward is trivial since you are moving down the tree, and there's always one way to go

  function git_down
        git checkout HEAD^
  end

When traversing forward you are moving up the tree, so you need to be explicit which branch you are targeting:

  function git_up 
        git log --reverse --pretty=%H $argv | grep -A 1 (git rev-parse HEAD) | tail -n1 | xargs git checkout
  end

Usage: git down, git up <branch-name>

If you want to see ahead, you can do this trick, as Git doesn't have strict command for it.

git log --reverse COMMIT_HASH..

Example

List of log history hashes:

A
B
C -> put this
D

using command git log --reverse C.., in output you will see B and A.

branchName=master; commitInOrder=1; git checkout $(git log --pretty=%H "${branchName}" | tac | head -n "${commitInOrder}" | tail -n 1)

where:

branchName equals branch name

commitInOrder equals a commit in order from very first commit in the selected branch (so 1 is the very first commit, 2 is second commit in branch, etc.)

To GUI and vscode users I would recommend using the extension git graph

enter image description here

I would use git-reflog and git-reset.

It is not the same case as you run git-bisect, but suppose you git-reset to commit C and want to move it back to commit F.

At the point, git-reflog looks like this:

$ git reflog show
4444444 (HEAD -> main) HEAD@{0}: reset: moving to 4444444
1111111 HEAD@{1}: commit: F
2222222 HEAD@{2}: commit: E
3333333 HEAD@{3}: commit: D
4444444 (HEAD -> main) HEAD@{4}: commit: C
5555555 HEAD@{5}: commit: B
6666666 HEAD@{6}: commit: A

Then, you can run git-reset to go back to any commit by specifying SHA1 hash or offset number from HEAD.

In your case, run git-reset as follows:

$ git reset 1111111

or

$ git reset HEAD@{1}

The shortest way to move forward for one commit is:

git checkout @{1}

Related