Question

I'm a not a git expert so this might look like a silly question.

I have local and remote repositories, I want to sync my local with the remote repository. I have many local changes, stashed changes, and few commits which are not yet pushed to remote.

One way can be to remove all local changes(using git clean), revert commits and than fetch/pull from remote. But I think there must be some single command which can do all this in one go. I tried using git reset --hard HEAD and then git pull but that gave me:

# Your branch and 'origin/master' have diverged,
# and have 1 and 9 different commits each, respectively.

Was looking at this question as well, but didn't help.

Was it helpful?

Solution

As commented, a git reset --hard origin/master would reset your master to upstream.

But: your current master (with its local commit) would be "lost" (at least, no longer visible).

So one step isn't the best approach.

I would recommend something like:

git checkout master
git fetch origin
git branch tmp
git reset --hard origin/master
git checkout tmp
git rebase master
git checkout master
git merge tmp
git branch -d tmp

That way, you rebase your local commit(s) on top of the updated master

x--x--x--x--x (master, origin/master)       x--x--x--x--x--y'--y' (tmp, master)
       \                                 =>
        y--y  (tmp)                           (after rebase+merge)

OTHER TIPS

This command will discard all local commits on a branch and reset it to mirror what is currently on the remote:

git pull
git reset --hard origin/your-branch

The pull command is to make sure what you have is the most up to date of the branch

The permanent fix if you always want to create a new branch on the remote to mirror and track your local branch(or vice-versa) is:

git config --global push.default current

I always configure my local git with this command after I do git clone. Although it can be applied anytime when the local-remote branch "Git fatal: The current branch has no upstream branch" error occurs.

Hope this helps. Much peace. :)

git fetch -[options]

Checkout:

git fetch --help

for the functionalities you can use

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top