Gitはコマンドの種類が多すぎるので、私がよく使うものだけをメモとして残しておきます。
状況に関わらず使うもの
terminal
・現在のディレクトリをgit管理下に置く
$ git init
・全ての変更、新規ファイルをステージング
$ git add -A
・特定のファイルの、特定の部分の変更だけをステージング
$ git add -p /app/hoge.txt
・コミット
$ git commit
・直前のコミットを取り消す(ファイルはそのままでコミット前の状態に戻す)
$ git reset --soft HEAD\^
・コミットメッセージを修正
$ git commit --amend
・コミット前の変更を破棄
$ git reset --hard
$ git clean -df .
・コミット履歴を確認
$ git reflog
・過去のバージョンに戻る
$ git reset --hard <commitのID>(git reflogで確認)
・現在の状態を確認
$ git status
・git管理から外す
$ git rm -r --cached hoge.html
Githubで管理する時に使うもの
terminal
・Github上のリポジトリと紐付け
$ git remote add origin https://github.com/<ユーザー名>/<プロジェクト名>.git
・Push(初回、masterブランチ)
$ git push -u origin master
・Push(2回目以降、masterブランチ)
$ git push
ブランチを分けて開発する時に使うもの
terminal
・他のブランチに移動
$ git checkout <ブランチ名>
・新規ブランチを作成して移動
$ git checkout -b <新規ブランチ名>
・今いるブランチのブランチ名を変更
$ git branch -m <新しいブランチ名>
・他のブランチの変更を取り込む
$ git merge <取り込みたいブランチ名>
・Push(masterブランチ以外)
$ git push origin HEAD
・ブランチ一覧を表示
$ git branch
・ブランチを削除
$ git branch -d <削除したいブランチ名>
・ブランチ名にfeatureという文字列を含むブランチを削除
$ git branch | grep feature | xargs git branch -d
・変更を退避
$ git stash -u
・退避リストを表示
$ git stash list
・退避した作業を適用(stash@{0}の部分は$ git stash listで確認)
$ git stash apply stash@{0}
・退避した作業を全て消す
$ git stash clear
・マージコミットをリバート
$ git revert -m1 26af64b29e58babde67ac46bhogehoge
revert用に新たにブランチ作る→revertする→PR出す
GitHubのUI上でもrevertできる
https://docs.github.com/ja/pull-requests/collaborating-with-pull-requests/incorporating-changes-from-a-pull-request/reverting-a-pull-request
・ブランチ切り替えの履歴を表示
$ git --no-pager reflog | awk '$3 == "checkout:" && /moving from/ {print $8}' | uniq | head
・最新のmasterブランチを、作業中のブランチに反映する
$ git fetch origin
$ git merge origin/master
・リモートのmasterブランチをベースに、ローカルに作業ブランチを作る
$ git checkout -b hoge_new_branch origin/master
・リモートで最新のmasterブランチ取り込んだあと、それをローカルに反映せずにcommitを重ねてしまった時の対応
$ git reset --soft HEAD\^
$ git stash -u
$ git pull origin feature/hogehoge
$ git stash apply stash@{0}
$ git commit -m "コミットメッセージ"
$ git push origin HEAD
Githubのリモートリポジトリを手元に持ってくる系
terminal
・リポジトリのファイル一式をダウンロード
$ git clone https://github.com/<ユーザー名>/<プロジェクト名>.git
・手元のファイルをリモートリポジトリの内容に合わせる
(git remote addで紐付けができている状態で)
$ git pull