Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git checkout automatically merges local modifications

I tried following commands on the shell

git init

echo "test1" > test1.txt
git add test1.txt
git commit -a -m "test1"

echo "test2" >> test1.txt

git branch test
git checkout test

text.txt now contains:

test1
test2

After checkout to branch test all local modifications from master get merged.

Why?

I expected that git refuses checkout to test because of the local changes. I expected that git asks for a commit or stash the local changes.

Edit: I used a bash script to execute this commands. I get following output:

r@r:/tmp/test$ ./createrepo 
Initialized empty Git repository in /tmp/test/.git/
[master (root-commit) 0407f5b] test1
 1 file changed, 1 insertion(+)
 create mode 100644 test1.txt
M       test1.txt
Switched to branch 'test'
like image 837
Razer Avatar asked Oct 10 '12 15:10

Razer


People also ask

Does git checkout automatically merge?

Git merging combines sequences of commits into one unified history of commits. There are two main ways Git will merge: Fast Forward and Three way. Git can automatically merge commits unless there are changes that conflict in both commit sequences.

Does git checkout overwrite local changes?

Checkout old commitsSince this has the potential to overwrite local changes, Git forces you to commit or stash any changes in the working directory that will be lost during the checkout operation. Unlike git reset , git checkout doesn't move any branches around.

How do I turn off auto merge in git?

In the merge box, click Disable auto-merge.

Does git checkout merge branches?

To merge branches locally, use git checkout to switch to the branch you want to merge into. This branch is typically the main branch. Next, use git merge and specify the name of the other branch to bring into this branch.


1 Answers

git tries hard to not lose possibly valuable data. In this case, it's not actually merging branches, as the changes in question have not been committed. Rather, when you do a git checkout, it attempts to preserve newly made but not committed yet modifications, so it checks out the commit you are requesting, and adds your uncommitted changes. If you really want to discard the uncommitted changes, use git checkout -f, or git checkout followed by git reset --hard HEAD. Sometimes, if the changes you have not committed yet can't be merged into what you're checking out cleanly, you'll get an error message and the checkout will fail.

like image 182
twalberg Avatar answered Sep 29 '22 13:09

twalberg