How to revert initial git commit?

前端 未结 9 519
死守一世寂寞
死守一世寂寞 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:52

    You can delete the HEAD and restore your repository to a new state, where you can create a new initial commit:

    git update-ref -d HEAD
    

    After you create a new commit, if you have already pushed to remote, you will need to force it to the remote in order to overwrite the previous initial commit:

    git push --force origin
    
    0 讨论(0)
  • 2020-11-30 16:53

    You can't. So:

    rm -rf .git/
    git init
    git add -A
    git commit -m 'Your new commit message'
    
    0 讨论(0)
  • 2020-11-30 16:54

    Under the conditions stipulated in the question:

    • The commit is the first commit in the repository.
    • Which means there have been very few commands executed:
      • a git init,
      • presumably some git add operations,
      • and a git commit,
      • and that's all!

    If those preconditions are met, then the simplest way to undo the initial commit would be:

    rm -fr .git
    

    from the directory where you did git init. You can then redo the git init to recreate the Git repository, and redo the additions with whatever changes are sensible that you regretted not making the first time, and redo the initial commit.

    DANGER! This removes the Git repository directory.

    It removes the Git repository directory permanently and irrecoverably, unless you've got backups somewhere. Under the preconditions, you've nothing you want to keep in the repository, so you're not losing anything. All the files you added are still available in the working directories, assuming you have not modified them yet and have not deleted them, etc. However, doing this is safe only if you have nothing else in your repository at all. Under the circumstances described in the question 'commit repository first time — then regret it', it is safe. Very often, though, it is not safe.

    It's also safe to do this to remove an unwanted cloned repository; it does no damage to the repository that it was cloned from. It throws away anything you've done in your copy, but doesn't affect the original repository otherwise.

    Be careful, but it is safe and effective when the preconditions are met.

    If you've done other things with your repository that you want preserved, then this is not the appropriate technique — your repository no longer meets the preconditions for this to be appropriate.

    0 讨论(0)
提交回复
热议问题