Home > Net >  Will git pull command overwrite non-commit changes
Will git pull command overwrite non-commit changes

Time:06-03

Git pull command will fetch merge remote branch to local branch . And if there are merge conflict between commits , you can resolves it locally .

But what if I never commit anything I changed locally and pull a remote updated branch ?

Will git ignores my local non-commit changes and straight off overwrite my local branch ?

Does this mean I should always commit before pulling to update local branch ?

CodePudding user response:

If you have local changes when you run git pull then the the command will just fail if it would overwrite your local changes (with an error message that tells you that is why it failed).

If you want to pull without losing local changes you can include --autostash in your pull command, then git will stash your local changes, run the pull, and then restore your changes from the stash.

CodePudding user response:

If you run git pull with local changes :

  • the git fetch part is not impacted by your changes, it may fail for known reasons (network error, invalid credentials ...)
    if it succeeds, your remote branches will be updated, and git pull will proceed to the next step
  • the git merge part will try to combine your local changes with the result of the merge, just like a regular git merge origin/mybranch would do

git merge has a number of safety mechanism to avoid deleting your local work.

For example, if file foo.txt needs merging and you have local changes on it, git will abort the merge and display the following message :

error: Your local changes to the following files would be overwritten by merge:
    foo.txt
Please commit your changes or stash them before you merge.
Aborting

If your local changes are "compatible" with proceeding with the merge (e.g: are on files which are not modified by the merge operation), git will proceed with the merge.


git pull (and git merge) have a --autostash option, which will make git automatically run git stash before the operation, and git stash pop after it if the operation is successful.

That way git will always proceed with the merge. Be aware, however, that you may have to resolve conflicts at two different steps: once for the merge, and one second time for the stash pop operation.


The merge operation may be a pull operation (if you run git rebase --pull, or if you turn git config pull.reabse true for example) ; in that case, git flat out refuses to proceed with the rebase if there are any uncommitted modifications.

Again, you can use autostash.

  • Related