I have an empty git repo in which first I create a hello.txt file with content "pulkitsharma".
After this I added it to staging and then commited the changes in master branch. Then I create
another branch named as "new_branch" and updated the content of hello.txt with
"pulkitsharma\[email protected]" and didn't staged for commit. Now after this when I
checkout to master branch the content of hello.txt is updated automatically . Can anyone tell
us why this is happening because i think that during checkout to master branch there should be
an error.Why is output of git checkout master is
"M hello.txt Switched to branch 'master' "
git init
vi hello.txt
git add .
git commit -m "hello.txt added to master branch"
git checkout -b new_branch
vi hello.txt
git checkout master
CodePudding user response:
git checkout
is clear:
To prepare for working on
<branch>
, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch.Local modifications to the files in the working tree are kept, so that they can be committed to the
<branch>
.
So your local modification (unstaged) to hello.txt remains even when you switch back to master
.
The OP adds in the comments:
Now I accidently checkout to
master
branch.
Then instead of showing up error and asking of either commit or stash why does it update the files inmaster
branch (without any extra commit in master branch)
As mentioned in "How to stop git auto-update when switching branches?", you would need to:
- either commit (
git commit -a -m "…"
) before doinggit checkout master
. - or
git stash
if you don't want to do a "temporary" commit.
Later on, dogit checkout new_branch && git stash pop
to retrieve your uncommitted code.