1
1

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コマンド

Last updated at Posted at 2025-05-22

よく使うGitコマンド

git commit

直前コミットのやり直し

git commit --amend

このコマンドを使うとコミットメッセージの編集画面がviなどで開くものの、行頭でシャープ記号など使うとコメントアウト扱いになって認識されず、個人的には使い勝手が悪いためよく使用するのは以下のパターン。

直前コミットのやり直し(コミットメッセージも同時に編集)
git commit --amend -m "#1234 修正1+修正2"

git reset

直前コミットの取り消し

git reset <option> HEAD~

または

git reset <option> HEAD^

直前のコミットをキャンセル(作業内容維持)
git reset --soft HEAD~
直前のコミットをキャンセル(作業内容破棄)
git reset --hard HEAD~

--soft:作業内容はそのまま維持してコミットだけ取り消し。

--hard:コミットを取り消した上で作業内容もリセット。

~ (チルダ) は『n世代前のコミットを指定』の意味。
^ (キャレット) は『複数の親コミットからコミットを指定』の意味。

そのため『nコミット前』を意図するなら ~ (チルダ) に癖付けするのが吉。
@gyokuto さん、ご指摘ありがとうございました!)

なおWindowsの場合は git reset --soft "HEAD~" のように、 HEAD~" で囲むらしい。

git push

強制プッシュ

git push -f <remote> <branch>

強制的にプッシュする
git push -f origin branchName

前述の git commit --amendgit reset などで歴史改竄したコミットを強制的にリモートへプッシュするときなどによく使用する。

ブランチ削除

Gitブランチを削除する (ローカル&リモート)

  • ローカル:git branch -d <branch>
  • リモート:git push <remote> --delete <branch>

今いるブランチは削除できないので、他のブランチにチェックアウト(移動)した後に実施。

ローカルのブランチを削除
git branch -d branchName
リモートのブランチを削除
git push origin --delete branchName

プッシュやマージされていないローカルブランチはオプション -d で削除できないため、オプション -D を使用。

ローカルのブランチを強制削除
git branch -D branchName

git fetch

ブランチ一覧を同期

ブランチ一覧を同期
git fetch -p

オプション -p は "prune" (取り除く) の意味。リモートに存在しないブランチはローカルからも削除される。

参考URL

git Book
git Reference | git reset
Git ブランチを削除する方法 (ローカル、リモート)
[Git]コミットの取り消し、打ち消し、上書き
【Gitコマンド】コミットメッセージ変更方法
【やっとわかった!】gitのHEAD^とHEAD~の違い
git reset の使い方と、主要オプション

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?