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

What 's the difference between "git reset" and "git checkout"?

1个答案

1

1. git reset

git reset is primarily used to revert previous commits. It can move the current branch's HEAD pointer to a specified state, typically for adjusting the commit history. Depending on the options used, git reset affects the working directory and staging area differently.

Usage Example:

Assume you have a commit history A-B-C-D, and you're currently on the latest commit D. If you want to revert the last two commits (C and D), you can execute:

bash
git reset --hard B

This will move the current branch back to commit B, resetting both the working directory and staging area to B's state, with commits C and D completely removed.

2. git checkout

git checkout is primarily used for switching branches or restoring files in the working directory. It can switch to a different branch or a historical commit's state, but it does not alter the commit history.

Usage Example:

If you want to view the code from the old commit B without changing the current commit history, you can use:

bash
git checkout B

This operation will display your working directory as B's commit state, but it will not move the HEAD pointer; you remain on the original branch.

Summary

In short, git reset is used to modify the commit history, potentially removing certain commits from the history; whereas git checkout is used to view different branches or historical states without altering the commit history. git reset is typically used when correcting erroneous commits, while git checkout is used for switching the working directory or restoring files.

2024年8月8日 09:20 回复

你的答案