Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are changes in one branch visible in another branch?

I execute the following sequence of commands:

git init rep
cd rep/
echo '111' > 1.txt
git add 1.txt 
git commit -m '1'
git checkout -b dev
echo '222' > 1.txt 
git checkout master
more 1.txt 

As a result of these commands I see

222

And I do not understand why. As you can see I create and go into the 'dev' branch. I do some changes there but I do not add and do not commit them. Why after going back from 'dev' to 'master' I do see the changes that I did in 'dev'? Shouldn't they stay in dev until I add, commit and merge them back to master?

like image 721
Roman Avatar asked Nov 24 '17 10:11

Roman


2 Answers

All the untracked files does not get impacted when you move in between different branches. As they belong to your filesystem and, GIT is unaware that to which branch these files belong. So when you commit those files, then GIT is aware of which files belong to which branch. And can remove or add files in working area based upon your branch.

like image 55
Raman Sharma Avatar answered Nov 18 '22 11:11

Raman Sharma


This is because you didn't commit your changes to branch dev. So the uncommitted changes is not tied to a parent commit yet.

Do

git checkout dev
git add .
git commit -m "changed 1.txt"

If you want to remove the changes do

git reset --hard master

EDIT

The dev and master branch are pointing to the same commit hash. Have a look inside the folder .git/refs/heads, this is where the branches are stored in seperate files. The content is the commit hash that the particular branch is pointing to. So the branch is simply a pointer to a commit.

In your particular case when you checkout master or dev, they both point to the same commit, and therefore the operation doesn't change the working tree. Otherwise you would get an error. Try changing something on the dev branch now, then you should get an error when git checkout master

like image 15
smerlung Avatar answered Nov 18 '22 11:11

smerlung