What should we be careful about with Git checkout?

Question

The command git checkout provides us with a way of pulling down a previously committed file into our working directory. What should we be aware of when using this command?

Answer

git checkout is sometimes referred to as a “dangerous command”. This highlights that it has some gotcha aspects that you should be aware of when utilizing it. For now, it’s most important to understand that any local (in your working directory) changes that you’ve made to the file being checked out will be gone. Git will simply copy the most recently-committed version of the file to your working directory, overwriting your copy. Therefore, it’s crucial that you avoid this command unless you absolutely know that you don’t want your unsaved local changes. Keeping this consideration in mind while using this command will save you the grief of losing your progress when all you wanted was to take a peak at what the previous commit looked like.

6 Likes

Hello, perhaps this is explained later on the course. But it seems that the file is overwritten (this was hard for me to understand because it wasn’t reflected on the codecademy console). My question is this. Are all files overwritten when you save multiple files as the upcoming lesson “More git add” explains? Does checkout restore all of them or just the one? Maybe we can write multiple files on the same line and get it to reverse them all.

3 Likes

Checkout command can behave differently depending what we want to achieve. Most common way - you will be switching to new branch with it, in doing so your basically replacing your local files with their version from repo. But in context of reversing changes - you can do it (you can specify files you want to adjust).
Probably this will be useful in context to this question link

1 Like

If we want to peak at the last commit, is it possible to write git checkout HEAD filename.txt > peak_commit.txt? Would this be considered best practice or an anti-pattern?

Are you sure it will override the local version of file when “checkout”???
Is there any way to keep both version?

The standard route would be to save any changes to your local files (e.g. with a commit) before performing a checkout. If you wanted to avoid a new commit consider something like git stash or find another way to back them up-


These posts on the subject are VERY helpful in visualizing what is really happening when you give the commands dealing with checkout / reset, etc…The whole sting of posts was eye opening! Reset Demystified

That’s a good heads up. I really appreciate it! ;D

1 Like