1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Gitコマンド各種

1
Last updated at Posted at 2024-08-25

【保存版】よく使うGitコマンドまとめ

普段よく使うGitコマンドを用途ごとに整理しました。


1. ステージング関連(add / 取り消し)

■ 追跡済みファイルのみをステージングする

git add -u

  • modified のみステージされる
  • Untracked files(新規ファイル)は含まれない

■ addだけを取り消す(編集内容は残す)

git restore --staged <ファイル名>

用途

  • git add したが、まだ commit していない
  • ステージだけを外したい

状態

  • 編集内容はそのまま残る
  • 再度 add 可能

2. ブランチ操作

■ リモートのみに存在するブランチから作成

git branch -r
git fetch
git checkout -b <作成ブランチ名>
origin/<リモートブランチ名>


3. stash(作業の退避)

※ 前提:追跡済みファイルのみ退避される

■ 編集内容を別ブランチへ移したい場合

git stash save "コメント"
git stash list
git checkout
git stash pop(@0, @1, @2と複数stashがある場合は@0を取り出す)

複数stashがある中から選ぶ場合

git stash list
git stash apply stash@{2}
git stash drop stash@{2}


4. コミットの修正

■ 直前のコミットを修正する

git commit --amend

用途

  • タイポ修正
  • ファイル入れ忘れ

手順

  1. git commit -m "test"
  2. git push -> PR作成までした
  3. 修正漏れがあったのでファイル修正
  4. git add
  5. git commit --amend
  6. 今いるブランチを確認(念のため)
    git branch --show-current
  7. 安全な強制プッシュ(おすすめ)
    git push --force-with-lease origin HEAD
    ※「自分が最後に見た時点のリモート先端」が変わってないなら上書きOK、もし誰かがその間にpushしてリモートが進んでたら push失敗して止まる(事故防止)
  8. PR上でも既存のメッセージをそのまま保存すれば1回目と2回目併せて1つのコミットになる

■ 最新コミットを取り消す(履歴を1つ戻す)

git reset --soft HEAD~1

状態

  • コミットだけ消える
  • add済み状態に戻る
  • 編集内容は残る

5. 特定コミット時点にファイルを戻す

① 履歴確認

git log --oneline

② 特定ファイルを復元

git restore --source <コミットID> <ファイル名>

③ 再コミット

git add <ファイル名>
git commit -m "指定コミットの状態に戻した"


6. 間違えてPullした内容を取り消す

git reset --hard HEAD@{1}

※ 直前のpullを取り消す


7. Pushしてしまったコミットを取り消す

※ 履歴を書き換えない方法

① コミットID確認

git log --oneline

② 打ち消しコミットを作成

git revert <コミットID>

③ Push

git push origin <ブランチ名>

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?