Kutay Demireren
Kutay Demireren

Reputation: 650

Stash / Commit before Pull Not to Lose Local Files

I'm having trouble with syncing my local repo with the remote repo on GitHub if both remote and local repos have changes. So, for example, if I haven't started working on a feature, before I start I can sync by simply running

git pull origin master

This is a simple one. However, while I am working on a feature on local, let's say my coworker had pushed new features to the remote so that the remote has changed also. I tried accomplishing syncing with both commiting and stashing before pull. So those codes,

git add .
git commit -m "message"
git pull origin master

or

git stash save "message"
git pull origin master
git stash pop

Both those two methods ended up with overwriting my local changes, so rather than putting the remote changes on the top of my local master branch, it overwrites my local files and the local changes dissepear.

What am I doing wrong ? I was referring to many documentation about git but I just can't accomplish that.

Thanks,

Upvotes: 5

Views: 3304

Answers (2)

Deepak Biswal
Deepak Biswal

Reputation: 4320

Setting your branch to exactly match the remote branch can be done in 2 steps:

git fetch origin
git reset --hard origin/master

If you want to save your current branch's changes before doing this , you can do:

git commit -a -m "Saving my work, for later use"
git branch my-saved-work

Now your work is saved on the branch "my-saved-work" in case you decide you want it back (or want to look at it later or diff it against your updated branch).

Upvotes: 1

Maroun
Maroun

Reputation: 95968

Let's assume you're working on my_branch, and made some changes there. Now your co-worker pushes to the master, you need to update yours:

git stash
git checkout master
git pull

Your master is synced with the changes.

Now you want to continue working on my_branch, so you

git checkout my_branch

and now you should stash pop the changes:

git stash pop

If no conflicts were detected, the merge will automatically work. Otherwise, you'll be asked to resolve them.

Upvotes: 4

Related Questions