乐闻世界logo
搜索文章和话题

What 's the difference between HEAD^ and HEAD~ in Git?

1个答案

1

In Git, both HEAD^ and HEAD~ are used to reference previous commits on the current branch, but their usage and meanings have some differences.

HEAD^

HEAD^ (sometimes written as HEAD^1) is typically used to represent the direct parent commit of the current commit. If the current commit is a merge commit (which has two parent commits), then HEAD^ defaults to the first parent commit. You can use HEAD^2 to access the second parent commit.

For example, if you have completed work on a feature branch and merged it into the main branch, the merge commit has two parent commits:

  1. The last commit of the feature branch (HEAD^1 or HEAD^).
  2. The last commit of the main branch before the merge (HEAD^2).

HEAD~

HEAD~ (equivalent to HEAD~1) also points to the direct parent commit of the current commit, but it can be combined with numbers to represent more distant ancestors. HEAD~n indicates traversing up n levels of parent commits. Each level up points to the immediate parent commit.

For example, if you want to review the third most recent commit on the current branch, you can use HEAD~3.

Summary

  • HEAD^ and HEAD~ function the same without a number or with 1, both pointing to the direct parent commit of the current commit.
  • HEAD^2 is used to access the second parent commit of a merge commit.
  • HEAD~n is used to access the parent commit n levels up from the current commit.

These operations are very useful in daily Git usage, such as code rollback, reviewing historical commits, and resolving conflicts.

2024年6月29日 12:07 回复

你的答案