Katrinna L Katrinna L - 4 months ago 18
Git Question

Pull from git while having unpushed commits

I have several commits that aren't pushed yet. But there're several new commits in the repository. I want to pull the new commits and push my commits, but I'm not sure what's the correct way to do this.
If I do a pull as is I think it tries to merge and I'm not sure what becomes of my commits, please suggest what's the solution for such situation.

Answer

You have two main options here, you can either merge the remote branch into your branch then push, or you can rebase your branch on the remote, and then fast-forward the remote branch.

Option 1: merge

git pull origin yourBranch           # does a fetch, followed by a merge
git push origin yourBranch           # push merged branch to remote

Option 2: rebase

git pull --rebase origin yourBranch  # does a fetch, followed by a rebase
git push origin yourBranch           # ideally this will fast-forward the remote,
                                     # meaning all your commits will be played on top

Merging will collapse your commits into a single merge commit which will appear in the remote branch, whereas rebasing will preserve your commits, in order, in the remote branch.

In either case, you won't lose the work you have done, though some (or all) of the commits you made might not be preserved in the remote branch if you go with the merge option.