Git checkout command

The git checkout command can be used for lot of activities in git, that is reason some simpler commands are added to the git like git switch and git restore commands. We can use git checkout to create branches, switch to new branches, restore files, and undo history also.

Important point on the concept of HEAD in git
• Usually, HEAD points to a specific branch reference rather than a particular commit.
HEAD is a pointer to the current branch reference.
• The branch reference is a pointer to the last commit made on a particular branch.

Your image is not available

When we make a new commit, the branch reference is updated to reflect the new commit. The HEAD remains the same, because it’s pointing at the branch reference.

Your image is not available

When we switch branches, HEAD is updated to point to the specific branch reference. In the above image we can see that the HEAD is pointing to Master.

If we switch to the Demo branch, using the command git switch Demo, HEAD is now pointing at the Demo branch reference.

Your image is not available

So, it means that HEAD usually refers to a branch not a specific commit.
We can use git checkout <commit-hash> to view a previous commit and decide we want to return to where we were before. When we checkout a particular commit, HEAD point at that commit rather than at the branch pointer, and when HEAD does not point to most recent commit of the branch, such state is called as Detached HEAD.

Your image is not available

Note:
We can use the git log command to view commit hashes. We just need the first 7 digits of a commit hash (We can also use the full hash code).

Bash

git checkout 6565tis

When we run the above command, we see the following message:

Detached HEAD
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 switching back to a branch.

Your image is not available

git checkout Head~1
git checkout supports a slightly odd syntax for referencing previous commits relative to a particular commit.
HEAD~1 refers to the commit before HEAD (parent)
HEAD~2 refers to 2 commits before HEAD (grandparent)
This is not essential, but I wanted to mention it because it's quite weird looking if you've never seen it.

Bash

git checkout HEAD~1
Your image is not available

Discarding changes
Suppose we have made some changes to a file but don't want to keep them. To revert the file back to whatever it looked like when we last committed, we can use:
git checkout HEAD <file name> to discard any changes in that file, reverting to the HEAD.
Because HEAD is usually pointing out to the last commit. So, when we run git checkout HEAD <file name>, git will replace the content of the specified file with the version from the last commit. This is useful if we have made changes to a file and want to discard those changes.