git.day/12 • See all at git.day
There are two git checkout
operations I'm sure you're familiar with:
git checkout ref
, such asgit checkout branch-name
to checkout a branch, orgit checkout hash123
to checkout a commit (detached HEAD), andgit checkout path/to/file
to restore a file back to the state in HEAD.
The latter operation, checking out a file to HEAD, didn't mention HEAD in the command. That's because many commands imply HEAD where a reference goes. This operation is disambiguated with git checkout -- path/to/file
; the use of --
delimits the reference before with the pathspec afterwards. Since no ref is provided, HEAD is implied.
While HEAD is implied, any ref can be given here. This will checkout the file to the state that it existed in any commit in the past, pointed to by any ref, such as a branch, hash or tag. The most common use for me is git checkout HEAD^ path/to/file
to restore a file back to the state of the previous commit.
This will remove any local changes to the file being checked out and stage the changes, placing them in both the working tree and the index. This may cause you to lose work in local changes made to the file. Check with git status
first to make sure you're not losing any work.
When path/to/file
cannot be confused as a reference, the delimiter --
is not required. While some other commands would error if both path/to/file
exists as both a branch and file path, in this case the command options are clear: path/to/file
will be treated as a branch.
$ git checkout a/b
M a/b
Switched to branch 'a/b'
Code language: Shell Session (shell)
This means the modified file at path a/b
was kept while the branch a/b
was checked out.