本記事ではファイルの変更を取り消すことができる、git checkoutコマンドについて解説しています。

- 漫画形式で読みやすく理解しやすい
- GitHubを使った実践的な内容も分かりやすい


Amazon Kindle Unlimitedに登録すると、月額980円で読み放題だからオススメだよ!



初回30日間は無料だから、まだ登録したことのない人はぜひ試してみてね!
変数名/関数名にもう悩まない!


- 美しいコードが書けるが自然と書けるようになる
- 他の開発者が理解しやすいコードになる


ワークツリーの変更を取り消す
git checkoutは、ブランチを切り替えたい時に使われるコマンドですが、それ以外にもワークツリー(自分の作業場所)で編集したファイルを編集する前の元の状態に戻すことができます。



Gitはどのようにしてワークツリー内のファイルを元の状態に戻しているんですか?



ステージにあるファイル情報をワークツリーに反映させることで元のファイル状態に戻しているよ!
ファイルを元の状態に戻す
ファイルを元の状態に戻すには、–の後に元の状態に戻したい「ファイル名」を指定します。
git checkout -- filename
Gitでは主に「-」を使いますが、ファイルを元の状態に戻すときは「–」を使っている理由は、ブランチ名とファイル名が同じだった場合Git側がどちらを指定しているのか正しく認識できるよう分けています。
ディレクトリを元の状態に戻す
ディレクトリを元の状態に戻すには、–の後に元の状態に戻したい「ディレクトリ名」を指定します。
git checkout -- directoryname
全ての変更を元の状態に戻す
現在いるディレクトリ配下の変更を全て元の状態に戻すには、–の後に「.」を指定します。注意点として、現在いるディレクトリより上の階層にあるファイルの変更は取り消すことができません。
git checkout -- .
【実践】ファイルを元の状態に戻す流れ
それでは実際にワークツリー内のファイルを元の状態に戻す流れを紹介します。既にステージにファイル情報(sample.txt)がある前提で解説していきます。ステージのファイル情報は以下の通りです。
テキスト1
まず始めにファイルに1行テキストを追加します。
テキスト1
テキスト2 #新規追加
git statusコマンドで現在の状況を確認してみましょう。
git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: sample.txt
no changes added to commit (use "git add" and/or "git commit -a")


sample.txtが変更されていることが確認できました。
それでは、git checkoutコマンドを使ってワークツリーで変更したファイルを元の状態に戻してみましょう。
git checkout -- sample.txt
sample.txtの中を確認してみると、「テキスト2」が削除され「テキスト1」のみ表示されていることが確認できます。
テキスト1
以上が、ワークツリー内のファイルを元の状態に戻す一連の流れになります。