Home > Software engineering >  Will git pull overwrite the code I just wrote
Will git pull overwrite the code I just wrote

Time:12-09

Suppose there is such a scenario: In the morning, I pulled the latest code, and then I made some changes to the code. When I wanted to push, because someone else pushed before me, my push failed, and then I need to pull the latest code first. I thought: Will the pull operation overwrite the code I wrote today. I checked some online posts, saying that it will overwrite my local code So I did a test: I wrote a 1.cpp with only header files and main functions in it, then I pushed it to GitHub, and then directly added a 2.cpp to GitHub to simulate other people's push operations. Then I modified the local 1.cpp, added a few test functions to it, and then I pulled in git bash, but after the pull was over, I found that the local 1.cpp was not covered by the 1.cpp on GitHub, and it was still the same as the original.

I use a translator, so please excuse me if the language offends

CodePudding user response:

pull operation will not necessary overwrite your files, it is not correct. pull operation will fetch remote branch, and integrate it into your local. And it means, that it will merge changes.

And this is what has happened in your case. You have pushed 1.cpp file to origin. Then modified it locally. Then you pulled branch again from origin - so it merged changes of that file. And git knows, that you have added something to that file, and it can merge those changes silently. If you would, for example, change header of that file - it would cause merge conflict, and git would ask you to resolve it. So you would have to decide which version of the file you will take, or how you will merge it.

But if you would have modified 1.cpp file on Github, and then would pull - then your local file would be overwritten. Because it will be "newer" than local, so git would merge those changes into your local file.

  •  Tags:  
  • git
  • Related