11 Revert to a previous commit (git checkout)

Key terms/commands:

  • git checkout: revert (i.e., checkout) a file to a previous state. You can also checkout your entire folder, but it is potentially a dangerous move (puts you in a detached HEAD; read the end of this chapter).

11.1 Going back to a specific version of a file (git checkout)

Make sure you are in your original workdir

Make some changes to foo.txt

## hello
## world
## whales are good
## A whole new world

Let assume we want to go back to a previous version of foo.txt.

Before going back to a previous state of a file, COMMIT what you have now!

## [master e9b18f4] Add 'A whole new world' to foo.txt
##  1 file changed, 1 insertion(+)

Recover the foo.txt that doesn’t have “A whole new world” in it (use HEAD~1 or unique identifier)

## Updated 1 path from 1b61113

Check what is in foo.txt

## hello
## world
## whales are good

Go back to the state where “A whole new world” is in the file

## Updated 1 path from 6d02667
## hello
## world
## whales are good
## A whole new world

11.2 Going back to an entire commit - Detached HEAD (CAUTION)

If you git checkout a previous commit without also specifying a file, you will revert the entire directory to a previous condition

## Note: checking out 'HEAD~1'.
## 
## You are in 'detached HEAD' state. You can look around, make experimental
## changes and commit them, and you can discard any commits you make in this
## state without impacting any branches by performing another checkout.
## 
## If you want to create a new branch to retain commits you create, you may
## do so (now or later) by using -b with the checkout command again. Example:
## 
##   git checkout -b <new-branch-name>
## 
## HEAD is now at 098e82d Merge changes from Github, whales are good

You should see a warning message about being in a ‘detached HEAD’. (Refer to the Glossary section in the Appendix for a brief overview on “HEAD” and “detached HEAD”.)

Use git checkout HEAD to return to most recent state.

BONUS - Detached HEAD

CAUTION 1: If you make commits while you are in a detached HEAD, returning to “master” (or any other branch) means those changes are loss (again, we will talk about branches soon).

A detached HEAD means you are not in a branch, and any changes you make will disappear when you switch back to a real branch (e.g., git checkout master). More about branching and how to prevent your works from disappearing in the next chapter!


You have now used checkout to look at the past version of a file!