0
1

Gitのローカルを戻す方法 〜Git statusで確認しよう~

Posted at

見出し

この投稿は初投稿となります。温かい目でご覧いただくとありがたいです!
アウトプットの一つとしてQiitaを使ってみます!
今年の16日から未経験のプログラマーとして働くのでGitを再度復習しようと思って投稿いたします。
Gitのローカルで間違えて変更してしまったものを元に戻す方法をまとめていきます。

ステージングされていないGitの変更を元に戻す方法

まずGit statusコマンドで現在のGitの状態を確認します!

new.html.erb
git status
On branch basic-login
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:   app/views/users/new.html.erb
        

(use "git add ..." to update what will be committed)
となっているのでまたGitにはステージングされいません!

間違えてGitの変更をした場合

git checkout <filename>

全て変更するにはこのコマンドを使います

git checkout .

結果をgit statutsで確認すると

git checkout app/views/users/new.html.erb
Updated 1 path from the index myapp % git status
On branch basic-login
nothing to commit, working tree clean

nothing to commit, working tree cleanとなっているので大丈夫ですね!

ステージングされているGitの変更を元に戻す方法

git checkoutコマンドを使ってもステージングされいて元に戻せない場合もあると思いますが、その場合はこのコマンドを使いました

git checkout HEAD -- [ファイル名]

全てを変更する場合

git reset

こちらも再度確認していきます  まずは参考のためにgit addしてgit statusで現在の状況を確認します。

git add .
myapp % git status
On branch basic-login
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   app/views/users/new.html.erb

先ほどと違いChanges to be committed:のところで次はコミットしてくださいというメッセージが出てるのgit addには成功しています。では先ほど紹介したコマンドを使います。

git checkout HEAD -- app/views/users/new.html.erb
myapp % git status
On branch basic-login
nothing to commit, working tree clean

元に戻りました!

未追跡のファイルがあり git checkoutでローカルの変更を戻せない時

当時、私はgit checkout .コマンドを使って全ての変更を元に戻そうと思った時このような状況になり、元に戻すことができませんでした。

git checkout .
Updated 1 path from the index
git status
On branch basic-login
Untracked files:
  (use "git add <file>..." to include in what will be committed)
        app/controllers/test_controller.rb
        app/helpers/test_helper.rb
        app/views/test/
        test/controllers/test_controller_test.rb

Untracked files:となっており未追跡のファイルが存在しているのでgit addコマンドを使ってステージングさせてから元に戻すかもしくは下記のコマンドを使いました。
ファイルを削除する方法

git clean -f

ディレクトリもファイルも一気に削除する方法

git clean -df
git clean -df
Removing app/controllers/test_controller.rb
Removing app/helpers/test_helper.rb
Removing app/views/test/
Removing test/controllers/test_controller_test.rb
git status
On branch basic-login
nothing to commit, working tree clean
0
1
0

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
0
1