3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

untracked filesでのgit reset --hardの罠

Posted at

要約

addした新規ファイルはgit reset --hardによって消えるので注意.

恐怖の git reset --hard

それはある夏の日のことです.
gitリポジトリの中で,untrackedファイルを作成し,git reset --hardを行いました.
(まだgitのリポジトリにaddもcommitもされていない新規のファイルのことを,git上ではuntracked filesと呼びます.)

touch foo   # 新規ファイルを作成
git status
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#         foo
# nothing added to commit but untracked files present (use "git add" to track)

git reset --hard   # untrackedファイルには影響しない

untracked fileがある状態でgit reset --hardをしても,それらのファイルには何の影響もありません.

しかし,untracked fileをaddした状態でgit reset --hardをすると大変なことになります(なりました).

touch foo   # 新規ファイルを作成
git add foo   # addする
git status
# Changes to be committed:
#   (use "git restore --staged <file>..." to unstage)
#         new file:   foo
git reset --hard   # addしたuntracked fileが消える

そうなんです.addしたuntracked filesが消えてしまいます.

これは,git addでインデックスに追加されたuntracked fileがgit reset --hardによって,
ファイルの存在ごとリセットされてしまうことで起こります.

対策:git reset --hard する前に

上記の問題の対策として,git resetしてからgit reset --hardするのがよいのではと思います.

git resetをするとインデックス登録がリセットされるため,untracked filesの状態に戻ります.
そして,git reset --hardで変更があるファイルだけリセットされます.

毎回git resetを打つのは面倒なので,.bashrcなどにエイリアスを登録しておきましょう.

alias git reset --hard='git reset && git reset --hard'

その他,良い対策方法あればご教授ください~

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?