git revert
safely undoes a specific commit by creating a new “undo” commit, so your history stays intact—even on shared branches (works for single, multiple, and even merge commits).
git revert
は、既存のコミットを元に戻すために使用される Git コマンドです。具体的には、元に戻したいコミットを打ち消す新しいコミットを作成します。これにより、プロジェクトの履歴を保持したまま変更を取り消すことができます。
基本的な動作の流れ
git revert <コミットハッシュ>
の形式で、取り消したいコミットを指定します。git revert HEAD
/ メッセージ編集を省くなら git revert --no-edit HEAD
git log --oneline
でハッシュ確認 → git revert a1b2c3d
git revert --no-edit HEAD~3..HEAD
git revert --no-commit HEAD~3..HEAD
→ 直す → git commit
Git Bash
# 直近3件(HEAD~3 から HEAD まで)を一気に戻す(自動でコミット)
git revert --no-edit HEAD~3..HEAD
# 個別に確認したい(最後に自分で commit)
git revert --no-commit HEAD~3..HEAD
git commit
# 離れたコミットを複数まとめて
git revert --no-edit <hash1> <hash2> <hash3>
マージを打ち消すときは、どちら側を“主線(親)”とみなすかを -m
で指定します。
Git Bash
# 親の並びを確認
git show <merge-hash>
# 親1を主線として取り消し
git revert -m 1 <merge-hash>
git add <直したファイル>
git revert --continue
(やり直すなら git revert --abort
)過去に行った revert
を、さらに revert
すると、当時の変更を復活できます。
git revert HEAD
。メッセージ編集を省くなら --no-edit
。git revert --no-edit HEAD~3..HEAD
。範囲の書き方がカギ。-m
で親番号を指定。git show <merge-hash>
で確認。git add
→ git revert --continue
。やり直しは --abort
。Git Bash
git revert HEAD
git revert --no-edit HEAD
git revert a1b2c3d
git revert --no-edit HEAD~3..HEAD
git revert --no-commit HEAD~3..HEAD
git commit
git revert --no-edit a1b2c3d e4f5g6h
git show <merge-hash>
git revert -m 1 <merge-hash>
git add <file>
git revert --continue
git revert --abort
Git Bash
git revert abc123
このコマンドは、ハッシュ値 abc123
のコミットを取り消すための新しいコミットを作成します。
注意点
git revert
は、元に戻したい変更を取り消す新しい履歴を作るため、履歴が保持され、チームでの作業時にも安心して利用できる手法です。一方、コミット自体が消えるわけではなく、あくまでその影響を取り消す動作です。
履歴を消さずに戻すのが git revert
の特徴です。