How to revert initial git commit?

前端 未结 9 561
死守一世寂寞
死守一世寂寞 2020-11-30 16:14

I commit to a git repository for the first time; I then regret the commit and want to revert it. I try

# git reset --hard HEAD~1

I get thi

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 16:43

    This question was linked from this blog post and an alternative solution was proposed for the newer versions of Git:

    git branch -m master old_master
    git checkout --orphan master
    git branch -D old_master
    

    This solution assumes that:

    1. You have only one commit on your master branch
    2. There is no branch called old_master so I'm free to use that name

    It will rename the existing branch to old_master and create a new, orphaned, branch master (like it is created for new repositories) after which you can freely delete old_master... or not. Up to you.

    Note: Moving or copying a git branch preserves its reflog (see this code) while deleting and then creating a new branch destroys it. Since you want to get back to the original state with no history you probably want to delete the branch, but others may want to consider this small note.

提交回复
热议问题