Git初心者なら必ず覚えるべきgit restoreコマンド

git restoreとは

指定されたファイルなどを「戻す」ことができるコマンド。

restoreとは「戻す」という意味。

ファイルなどを戻すコマンドはすでにほかにもあるが、git restoreのほうがわかりやすいのでこちらを使用したほうが良いだろう。

git restoreはバージョン2.23.0から追加されたので知っている人はほかのコマンドに比べて少ない。

保存前に戻す

例えば以下のようなfoo.txtを作成してadd後にcommitしたとする。

ねずみ
うし
ねこ

そのあと「ねこ」を「とら」に変えて上書き保存する。

ねずみ
うし
とら

このあと上書き保存前の「ねこ」に戻したくなったときにgit restore foo.txtを実行すれば元に戻すことができる。

git restore foo.txt

これだけだとgit checkout foo.txtと変わらないが、git restoreはgit checkoutでは戻せないものも戻せる。

addされる前に戻す

git checkout だとファイルを上書き保存してaddすると元に戻せないが、git restoreだと-Sオプションを付ければ戻すことができる。

git restore -S foo.txt

commitされる前に戻す

foo.txtの中に子・丑・寅と書かれてある箇所を子・丑・虎と修正してコミットしたとする。

しかし、子・丑・寅のほうが正しいのでfoo.txtをコミット前の状態に戻したいことがあったとする。

通常はgit resetやgit revertが使用されるがgit resetのようにcommit自体を取り消さず、git revertのようにcommitに戻したことを残さずファイルにまず変更を加えたい場合はgit restore -s HEAD^ foo.txtで戻したほうが都合が良い。

git restore -s HEAD^ foo.txt

git restore -sはコードのある特定部分や画像などを一時的に前のものに変更してチェックしたいときなどに便利だ。

例えばウニのサイトを作成して数日後にウニの画像(uni.png)をバフンウニからムラサキウニに変更してコミット、その後CSSなども修正してコミットしてもgit log --onelineでlogを表示して変更履歴とハッシュ値がわかれば、以下のように変更前のハッシュ値を指定することで簡単に特定の画像だけ戻すことができる。

$ git log --oneline
9eeef48 CSSを修正
81a35c7 うにの画像をムラサキウニに変更
cf58346 JSを修正
8fa2025 うにのサイトを作成
 git restore -s cf58346 uni.png

git restoreは-pも使える

前述の画像の場合はファイルをそのまま戻せば良いが、コードの場合はコード修正時に3行目と9行目を修正してコミットしたが、3行目の部分だけ戻して9行目はそのままにしたいこともある。

git restoreは-pを付けることで修正箇所をブロック分割してブロック別の修正箇所を反映させるかどうかを選択できるようになる。

分割されているブロックを再分割する場合は「s」を選択して、反映させるなら「y」、反映させないなら「n」を選択する。

$ git restore -p -s 0cb98071 index.js
diff --git b/index.js a/index.js
index b8c1d7e..a38fc69 100644
--- b/index.js
+++ a/index.js
 const year = new Date().getFullYear()

 if (year === 2021) {
-  console.log('olynpic & paralympic year')
+  console.log('olynpic year')
 } else {
   console.log('not olynpic year')
 }
-
-console.log('process done')
(1/1) Apply this hunk to worktree [y,n,q,a,d,s,e,?]? s
Split into 2 hunks.
 const year = new Date().getFullYear()

 if (year === 2021) {
-  console.log('olynpic & paralympic year')
+  console.log('olynpic year')
 } else {
   console.log('not olynpic year')
 }
(1/2) Apply this hunk to worktree [y,n,q,a,d,j,J,g,/,e,?]? y
 } else {
   console.log('not olynpic year')
 }
-
-console.log('process done')
(2/2) Apply this hunk to worktree [y,n,q,a,d,K,g,/,e,?]? n

ちなみにs, y, nなどが何の略かは「?」を入力すれば説明が表示される。

(1/1) Apply this hunk to worktree [y,n,q,a,d,s,e,?]? ?
y - apply this hunk to worktree
n - do not apply this hunk to worktree
q - quit; do not apply this hunk or any of the remaining ones
a - apply this hunk and all later hunks in the file
d - do not apply this hunk or any of the later hunks in the file
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help
カテゴリーgit