Search code examples
gitgit-push

Why do I have to --force my git commits


i have several git repositories set up and everytime i setup a new one and i do the first commit and push, this command fails git push origin master and i get some error about how it failed to push some refs.

----@--------- /c/git/repo/---- (master)
$ git push origin master
--------------------------------
--------------------------------
To -----------------------------
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/-----/----.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.

however if i do a git push --force origin master it works, why is that and why do i have to do it everytime?


Solution

  • This error...

     ! [rejected]        master -> master (non-fast-forward)
    

    ...means that the remote repository has changes that are not yet in your repository. If you are creating a repository on GitHub, it's possible to create a non-empty repository if you ask GitHub to pre-populate your repository with a .gitignore or README file.

    In any case, when you see this error, rather than using --force (which will overwrite any changes in the remote repository), you should probably just run:

    git pull
    

    This will bring down any changes and merge them into your local repository, at which point a git push should work just fine.

    You can also clone the remote repository to another directory and inspect it's contents if you're not sure what's there.