Referring to the previous/next commit in git?

2019-02-11 21:52发布

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?

标签: git commit
3条回答
可以哭但决不认输i
2楼-- · 2019-02-11 22:05

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`
查看更多
来,给爷笑一个
3楼-- · 2019-02-11 22:07

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.

查看更多
戒情不戒烟
4楼-- · 2019-02-11 22:11

Inspired by @cexbrayat's answer, I find it useful to think of it this way:

How to refer to something in a commit's ancestry, where a commit can have multiple parents:

  • ^n specifies which parent

  • ~n specifies which generation

Both default to one.

查看更多
登录 后发表回答