The Git checkout command is deceptively powerful and is something I end up using every day to accomplish various tasks. Let’s begin by reading the definition:
Updates files in the working tree to match the version in the index or the specified tree. If no pathspec was given, git checkout will also update HEAD to set the specified branch as the current branch.
Most of the power in git checkout
comes from the fact that it can act on branches as a whole, directories or single files. This flexibility can be leveraged to make it do more than just switching branches.
Most of the tips below build on each other, but I will list them separately in order to have this serve as a quick lookup.
Any changes made to files in your working directory can be discarded by using:
git checkout .
The literal .
(dot) here signifies to discard all changes in the working tree recursively.
Any changes made to a single file in your working tree can be discarded by using:
git checkout path/to/file
Any changes made to files in a single directory in your working tree can be discarded by using:
git checkout path/to/dir
You can also specify a branch, both remote and local to restore a given version of a file. Here we want to restore the file to the version it had on our upstream branch named “feature-branch”:
git checkout origin/feature-branch -- path/to/file
However, we can also select a local branch:
git checkout feature-branch -- path/to/file
Note that “feature-branch” does not have to match the branch you are currently on. I often find myself doing the following to restore a file to the version present at the main branch.:
git checkout origin/main -- path/to/file
This also works if you deleted a file in your current branch, but it exists on a different branch, both local and remote.
You can also specify a branch, both remote and local to restore a given version of a file
git checkout origin/feature-branch -- path/to/directory
This is actually just an extension of restoring a previous version, but I have seen several times that people will use the UI to navigate through commits, finding the file and copying the contents directly. Instead we can use the following:
git checkout path/to/deleted/file
You won’t get autocomplete for the filename if it was deleted on your current branch, and you want to restore it, but it will still work!
If the file was deleted in a previous commit, we can find the hash of that commit and use:
git checkout <commit-sha> -- path/to/file
As always, this also works for directories:
git checkout <commit-sha> -- path/to/directory