Master: git checkout
In this video, we'll look at some of the additional uses for
In init: git checkout we covered how do use
git checkout to switch branches as well as create and switch branches in one step with the
There are also two other uses for
The first is to checkout a file from a previous commit.
Let's demonstrate this by making some changes to a file and running
Notice Git tells use we can use
git checkout to discard these changes by running:
git checkout -- file-2.txt
If we run
git status again, we'll see that we are back to a clean state.
Let's take a second to break this command down.
The command we ran was really a shorthand for
git checkout HEAD file-2.txt. However, HEAD can be omitted as it's the default.
When you omit the commit reference, it's best to use the path separator of
-- to avoid a scenario where the name of the file you want to checkout matches a branch name.
git checkout master.
git checkout accepts a commit, this means we could checkout a file from a previous commit.
For example, to checkout File 1 from our initial commit, we could run:
git checkout SHA file-1.txt.
If we output the contents of File 1, we'll see that it's again empty just as it was in our initial commit.
Finally, we can use
git checkout to restore the repository to a previous point in time by passing it a commit SHA.
Let's demonstrate by using the same commit SHA to restore our repository to the initial commit.
So I'll run
git checkout and pass it the commit SHA.
Immediately we receive a warning that we are in a detached HEAD state. This sounds a little scary, but really all it means is we are not on a branch. As noted, you can make commits, but Git will not track them unless you create a new branch.
This is useful if we want to browse a previous version of the repository.
However, if you want to make changes to a previous version of the repository, it's better to create a branch from the previous version.
We can do by passing a second argument to
git branch. For example:
git branch initial-branch SHA
git checkout -b initial-branch SHA
If we run
git log, we'll see our commit history has been restored all the way back to our initial commit.