git resetで直前のコミット、n個前のコミットを取り消す方法
git resetで直前のコミット、n個前のコミットを取り消すには以下のようにします。
$ git add a.txt $ git commit -m "1st commit" $ git add b.txt $ git commit -m "2nd commit" $ git add c.txt $ git commit -m "3rd commit" $ git log --oneline # このようなコミット履歴の状態で、下記それぞれの場合の結果を示す b806f2c (HEAD -> main) 3rd commit 4ccd01d 2nd commit 2be1aea 1st commit
直前のコミットを取り消す(--softの場合、変更はステージングされた状態で残る)
$ git reset --soft HEAD~ # HEAD~またはHEAD^で直前 $ git status On branch main Changes to be committed: (use "git restore --staged ..." to unstage) new file: c.txt $ git log --oneline 4ccd01d (HEAD -> main) 2nd commit 2be1aea 1st commit
2個前のコミットまで取り消す(--softの場合、変更はステージングされた状態で残る)
$ git reset --soft HEAD~2 # HEAD~nでn個前まで $ git status On branch main Changes to be committed: (use "git restore --staged ..." to unstage) new file: b.txt new file: c.txt $ git log --oneline 2be1aea (HEAD -> main) 1st commit
直前のコミットを取り消す(--hardの場合、作業ディレクトリの変更もリセットされるので注意)
$ git reset --hard HEAD~ HEAD is now at 4ccd01d 2nd commit $ git status On branch main nothing to commit, working tree clean $ git log --oneline 4ccd01d (HEAD -> main) 2nd commit 2be1aea 1st commit
2個前のコミットまで取り消す(--hardの場合、作業ディレクトリの変更もリセットされるので注意)
$ git reset --hard HEAD~2 HEAD is now at 2be1aea 1st commit $ git status On branch main nothing to commit, working tree clean $ git log --oneline 4ccd01d (HEAD -> main) 2nd commit 2be1aea 1st commit