ritesh9984
ritesh9984

Reputation: 418

What does Git actually do when I run git checkout branch_name?

I have one repository which is called test-repo.

Right now, I have two branches on that repository, called:

  1. master
  2. master-bkp

Both branches contains only one file called test.txt.

test.txt in master contains

hello I am here

and test.txt in master-bkp contains

hello I am there

Now, in my local repository I write:

git checkout master
git merge master-bkp

Now test.txt in master contains

hello I am here
hello I am there

Can someone explain how Git works internally when I trigger these two commands?

git checkout master
git checkout master-bkp

Note : Please don't give opinions on git checkout, I need an explanation about internal logic behind it.

Upvotes: 1

Views: 17034

Answers (1)

scharette
scharette

Reputation: 9987

Git checkout is well documented, this is from the doc:

Updates files in the working tree to match the version in the index or the specified tree. If no paths are given, git checkout will also update HEAD to set the specified branch as the current branch.

Since I know you can read documentation here is how I see it. Git is a revision control system that provides many tools in order to manage your code history. Since you have many branches I will assume you understand correctly how they work. Checkout is only a command you use to move to others branches. The main goal is to updates files in the working tree so you get the data associated with a certain branch.

Behind the scenes

There is no magic. Has it said in the doc it only update HEAD so you are on the right branch. this is it. Also, as @ quetzalcoatl pointed out, it is important to know that git checkout performs a change detection which forbids changing branches while having uncommited work. Performing a git checkout can therefore be considered 'safe'.

Note

Sometimes beginners have a hard time understanding the difference between git checkout and git reset, even though they're completely different. The easiest way to see it in my opinion is :

What do you want to update ?

If the answer is my current branch go read the documentation on git reset. If your goal is to update your working tree based on another branch then git checkout is what you're looking for.

There is only one exception to this statement. If your goal is to overwrite one file, you can use git checkout, take a look at this answer.

Upvotes: 3

Related Questions