Git: merge behind changes

Scenario:

  • Computer A and Computer B have each cloned a git repository from Github.
  • On Computer A, I make changes to a repository, commit, and push to Github.
  • On Computer B, I make changes to other, unrelated files, and commit.
  • On Computer B, I try to push, but cannot because I forgot to pull my changes first.
  • On Computer B, I pull changes, and git creates a “Merge branch ‘master’ of github.com:user/repo” commit.
  • On Computer B, I push changes to Github, but have an annoying and unnecessary “Merge” commit in the commit history.

How can I use git merge to place the merge commit before all my commits that have not been pushed? It’s okay if this messes up the SHAs of the unpushed commits.

Do I need to git rebase something?

  • Merging a git stash with the current head
  • Best practice for Qt translations and git
  • How to merge to get rid of head with Mercurial command line, like I can do with TortoiseHg?
  • Git: is it safe to rebase a branch already merged?
  • Showing commits made directly to a branch, ignoring merges in Git
  • git checkout automatically merges local modifications
  • What is the default behaviour of “Resolve using theirs” in git
  • subversion merge - “has different repository root than”
  • 2 Solutions collect form web for “Git: merge behind changes”

    Simplest way to avoid “annoying” merge commit:

    git pull --rebase
    

    This would automatically rebase your changes on computer B such that history appears to be linear. For more information about rebase, look at this answer.

    If you have already pushed your merge commit from computer B to github, then it is too late: this merge commit will stay there forever. If not, you can still rebase. But it is easier to simply git pull --rebase to avoid it in the future.

    If you want to git pull has a rebase behaviour by default, you can also put this in your configuration:

    git config --global branch.autosetuprebase always
    

    This option in the configuration will set the rebase behaviour when you pull for every branch. If you want to do a pull with a merge after setting this you can do it with the option --no-rebase.

    git pull --no-rebase
    
    Git Baby is a git and github fan, let's start git clone.