Reset and Checkout Files in Git

hustnzj發表於2022-09-09

Normally, we use git reset to move the current branch to a new commit and optionally updates the working directory to match. But when we pass a file path, git reset updates the staging area to match the given commit and leaves the working directory alone, and it doesn’t move the current branch pointer. In other words, this form of git reset can be used to unstage a file.
This behavior is described in the manual:

git reset [-q] [<tree-ish>] [--] <pathspec>..., git reset [-q] [--pathspec-from-file=<file>
       [--pathspec-file-nul]] [<tree-ish>]
           These forms reset the index entries for all paths that match the <pathspec> to their state at
           <tree-ish>. (It does not affect the working tree or the current branch.)

           This means that git reset <pathspec> is the opposite of git add <pathspec>. This command is
           equivalent to git restore [--source=<tree-ish>] --staged <pathspec>....

           After running git reset <pathspec> to update the index entry, you can use git-restore(1) to check
           the contents out of the index to the working tree. Alternatively, using git-restore(1) and
           specifying a commit with --source, you can copy the contents of a path out of a commit to the
           index and to the working tree in one go.

The git checkout we’ve been using updates the working directory and switches branches. If we add a file path to git checkout, it reverts that file to the specified commit.
This behavior is described in the manual:

git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <pathspec>..., git checkout
       [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] --pathspec-from-file=<file>
       [--pathspec-file-nul]
           Overwrite the contents of the files that match the pathspec. When the <tree-ish> (most often a
           commit) is not given, overwrite working tree with the contents in the index. When the <tree-ish>
           is given, overwrite both the index and the working tree with the contents at the <tree-ish>.

Examples

vi blue.html # make any changes
git add blue.html
git status
git reset HEAD blue.html
git status
git add blue.html
git checkout HEAD blue.html
git status

Conclusion

The file-path behavior of git reset and git checkout both take a committed snapshot as a reference point. But git reset only update the staging area and git checkout updates both the staging area and the working directory.

References

Ry’s Git Tutorial

本作品採用《CC 協議》,轉載必須註明作者和本文連結
日拱一卒

相關文章