Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

People also ask

How do I go backwards in git?

Use git checkout & the ID (in the same way you would checkout a branch) to go back: $ git checkout <commit-id> . Don't forget the final ' .

How do I jump back from a commit?

To jump back to a previous commit, first find the commit's hash using git log . This places you at commit 789abcd . You can now make new commits on top of this old commit without affecting the branch your head is on. Any changes can be made into a proper branch using either branch or checkout -b .


I've experimented a bit and this seems to do the trick to navigate forwards (edit: it works well only when you have a linear history without merge commits):

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

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

Explanation:

  • 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~'

I believe you can do:

git reset HEAD@{1}

To go one commit forward in time. To go forward multiple commits, use HEAD@{2}, HEAD@{3}, etc.


All you need to get clear, not detached head state is to reset, not checkout.

git reset HEAD@{1}

This is what I'm using to navigate back and forth.

moving to next commit

function n() {
    git log --reverse --pretty=%H master | grep -A 1 $(git rev-parse HEAD) | tail -n1 | xargs git checkout
}

moving to previous commit

function p() {
    git checkout HEAD^1
}

Say F is the latest commit on trunk (insert your own branch name here) ... you can refer to it as trunk~0 (or just trunk), E as trunk~1, D as trunk~2 etc.

Take a look in your reflog for yet more ways to name commits.