1

I have done 4 wrong commits and want to go back to old state. Hence tried something like this (reference)

    # Resets index to former commit; replace '56e05fced' with your commit code
git reset 56e05fced 

# Moves pointer back to previous HEAD
git reset --soft HEAD@{1}

git commit -m "Revert to 56e05fced"

# Updates working copy to reflect the new commit
git reset --hard

and I got a message

HEAD is now at 56e05fced

after this I tried git push origin master to make sure the above changes are moved to master branch. But it throws an error to me

  ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'xxxxxxxxxxxx.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

how can I fix the issue here. (I don't want to pull the old master again as suggested in the above message)

None
  • 5,582
  • 21
  • 85
  • 170

1 Answers1

1

Pushing a local branch to origin after resetting the local branch to an old commit is a destructive operation as it will delete these commits in origin. Therefore you get this error unless you use git push --force. However, use force with care as it allows you to do push even if it is destructive. Make sure you fully understand the consequences before using --force.

For example, if anyone else has pushed to master branch since 56e05fced you will deleted those commits as well.

Consider using git revert instead of git reset. revert creates a new commit that is the inverse of the erroneous commit. The end result is the same as deleting the commit but a safer option as it does not delete anything in the history. However, you need to revert one commit at the time and start with the most recent to avoid conflicts. Reverting commits also leaves a trace in the history where each erroneous commit will remain in the history as well as the inverse commit created by revert.

TheIceBear
  • 2,912
  • 9
  • 23