Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referring to the previous/next commit in git?

Tags:

git

commit

I have seen git commands use a syntax such as HEAD~, but I haven't been able to find this syntax in the Git Reference Manual.

Here is what I have understood: <commit>~<n> refers to the commit <n> steps earlier than <commit> (where <n> is an integer number), and commit~ simply means the same and that <n> implicitly is one.

Now, is this correct? In that case, does this always work? What if <commit> is the result of a merge between two branches, which commit will then <commit>~ refer to? Is there some corresponding syntax for referring to the next commit or the commit <n> steps later?

like image 922
HelloGoodbye Avatar asked Apr 17 '13 14:04

HelloGoodbye


People also ask

How do you jump to a previous 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 .

How can I see the code of a previous commit?

All that you have to do is go on to the file that you committed on and go to the history for it, then select the earliest commit with the <> icon to view the code at that time.

How do I show previous changes made with commit message?

If you have the hash for a commit, you can use the git show command to display the changes for that single commit. The output is identical to each individual commit when using git log -p .


2 Answers

You have a very clear explanation of how this works in the chapter on Acenstry References in Pro Git:

  • ~ is used to get the first parent.
  • ^ can be used to get the other parents (^2, for example, for a merge).

But you don't have a simple way to reference the next commit, even if there are more convoluted ways to get it.

like image 184
cexbrayat Avatar answered Sep 30 '22 12:09

cexbrayat


To simply answer the question from title (since that's what got me here from Google):

To checkout the previous commit:

git checkout HEAD^ 

To checkout the next commit (assuming there's no branching):

git checkout `git log --reverse --ancestry-path HEAD..master | head -n 1 | cut -d \  -f 2` 
like image 22
Hubert OG Avatar answered Sep 30 '22 14:09

Hubert OG