gitコマンドの使い方 ~ git revert ~

git revert コマンド概要

git revertは特定のcommitの内容を取り消したい場合に、逆向きの変更を加えたcommitを作成するコマンドです。

commitを取り消すコマンドには他にgit resetコマンドがありますが、違い次の通りです。

コマンド特徴
git revertcommitが作成されるため取り消した履歴が残る
git resetcommitそのものが削除されるため履歴が残らない

git revert コマンドの使い方

git revert [commit-hash]

取り消したいcommitのハッシュ値を指定して実行します。

例.以下の手順でrevertコマンドでcommitを取り消した場合です。

  • file-A.txtに文字列「aaa」を入力しcommit①を作成
  • file-A.txtに文字列「bbb」を追記しcommit②を作成
  • revertコマンドでcommi①を取り消すcommit③を作成

commit①作成

(master)
$ echo 'aaa' > file-A.txt

(master)
$ git add -A

(master)
$ git commit -m '1st commit'
[master (root-commit) 27d9d33] 1st commit
 1 file changed, 1 insertion(+)
 create mode 100644 file-A.txt

 

commit②作成

(master)
$ echo 'bbb' >> file-A.txt

(master)
$ git add -A

(master)
$ git commit -m '2nd commit'
[master 5938f0a] 2nd commit
 1 file changed, 1 insertion(+)

 

revertコマンドでcommit②を取り消し

(master)
$ git log --oneline
5938f0a (HEAD -> master) 2nd commit
27d9d33 1st commit

(master)
$ git revert 5938f0a

commitメッセージを入力する画面に切り替わる

Revert "2nd commit"

This reverts commit 5938f0a341945a4a28bf45dba4f44924c1ad1506.

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch master
# Changes to be committed:
#       modified:   file-A.txt
#

 

commit②の内容が取り消しされているか確認

(master)
$ git log --oneline
4d6d662 (HEAD -> master) Revert "2nd commit"
5938f0a 2nd commit
27d9d33 1st commit

(master)
$ cat file-A.txt
aaa

取り消し用のcommit「Revert “2nd commit”」が作成されている

file-A.txtの内容を確認すると「aaa」の状態に戻りました。

git revert オプション

-e または –edit

git revert [commit-hash] --edit

revertのコミットメッセージを編集する場合に指定します。

デフォルトオプションですので、何もオプションを指定しない場合はこのオプションが有効になります。

 

–no-edit

git revert [commit-hash] --no-edit

revertのコミットメッセージを編集しない場合に指定します。

 

git revert の全てのオプションを確認する方法

以下のコマンドを実行するとブラウザでgit revertのヘルプページが表示される

git revert --help

Gitコマンドの使い方一覧

Git設定git config ~Gitリポジトリの設定~
初期化git init ~ローカルリポジトリの構築~
ログ&設定値確認git log ~commitログの履歴確認~
git status ~作業ディレクトリとステージングエリアの更新状態確認~
git diff ~commitやファイルの差分確認~
git show ~commitの内容確認~
git remote ~リモート追跡ブランチのリモートリポジトリの設定確認~
git reflog ~HEADやブランチの移動履歴の確認と整理~
ステージングエリアの操作git add ~ステージングエリア(インデックス)にファイル追加~
git ls-files ~ステージングエリア(インデックス)のファイル一覧表示~
git rm ~ステージングエリア(インデックス)のファイル削除~
ローカルリポジトリの操作git commit ~blobやtreeなどをまとめたcommitを作成~
git merge ~指定したブランチの内容を取り込み新しいcommitを作成~
git rebase ~commitの履歴の整理~
git cherry-pic ~特定のcommitの変更内容だけを取り込む~
git cat-file ~リポジトリのオブジェクト(commit,tree,blob)の内容表示~
git revert ~指定したcommitを取り消すcommitを作成~
commitのエイリアスなどgit branch ~commitツリーの枝(ブランチ)を作成~
git tag ~リリースなどのタイミングで特定のcommitに名前を付ける~
git stash ~commitを作成する前の変更内容を一時保存~
commitの内容をステージングエリアや作業ディレクトリに反映git checkout ~commitをステージングエリアと作業ディレクトリに展開~
git reset ~HEADの位置やステージングエリアと作業ディレクトリの内容を変更~
リモートリポジトリとのやり取りgit clone ~リモートリポジトリからローカルリポジトリ作成~
git fetch ~リモートリポジトリのブランチをローカルリポジトリに反映~
git pull ~git fetchとgit mergeを同時に行う~
git push ~ローカルリポジトリのブランチをリモートリポジトリに反映~