よく使うGitコマンド

新しいブランチを作成

# リモートの最新状態を取得(必要に応じて)
git fetch origin

# リモートの[master]ブランチを親に[feature/mybranch]を作成
git checkout -b feature/mybranch origin/master

ブランチを切り替える(チェックアウトする)

# [feature/mybranch]ブランチに切り替える
git checkout feature/mybranch

ブランチ名を変更

# 現在チェックアウト中のブランチ名を[feature/new]に変更
git branch -m feature/new

ブランチを削除

現在チェックアウト中のブランチは削除できないので注意。

# [feature/old]ブランチを強制的に削除
git branch -D feature/old

現在の変更をステージングしてコミットする

# 変更内容を確認(必要に応じて)
git status -s

# 全ての変更をステージング
git add .

# コミット
git commit -m "コミットメッセージ"

リモートにプッシュする

# [feature/mybranch]ブランチをプッシュ
git push -u origin feature/mybranch

別ブランチの内容を取り込む

# リモートの最新状態を取得(必要に応じて)
git fetch origin

# リモートの[master]ブランチを取り込む
# pull/merge/rebase は、いずれか適した方法を選ぶ
git pull origin/master
git merge origin/master
git rebase origin/master

現在の変更を全て破棄する

# 変更内容を確認(必要に応じて)
git status -s

# 変更を全て破棄
git checkout .

現在の変更を退避する/適用する

# 退避
git stash -u

# 適用
git stash apply

特定のコミットだけ取り込む

# 取り込む
git cherry-pick [commitID]

特定のファイルだけ取り込む

# リモートの最新状態を取得(必要に応じて)
git fetch origin

# [index.php]のみ、リモートの[master]ブランチと同じ状態にする
git checkout origin/master index.php

コンフリクト時、どちらかの内容を強制的に採用する

# [feature/mybranch]で作業中、リモートの[master]をマージしようとしてコンフリクトが発生したとする
git fetch origin
git merge origin/master

# [feature/mybranch]ブランチの内容を採用する
git checkout --ours

# リモートの[master]ブランチの内容を採用する
git checkout --theirs

# 特定のファイルのみを対象にする場合はファイルパスを合わせて書く
git checkout --ours index.php
git checkout --theirs index.php

ひとつのコミットにまとめる

feature/old ブランチで細かくコミットしていたけど最終的にひとまとめにしたい場合

# リモートの[master]ブランチを親に、まとめ用のブランチ[feature/new]を作成
git checkout -b feature/new origin/master
# [feature/old]ブランチの変更を全て持ってくる(※コミットはされていない状態)
git merge --squash feature/old

# コミット
git add .
git commit -m ""