LoginSignup
144
163

More than 5 years have passed since last update.

Githubで一番有名なGit TIPS集

Last updated at Posted at 2017-09-01

似たようなTIPSは山ほどあるけど、その中でもGitHubで最も多くのStarを集めているgit-tipsを日本語訳してみます。

Tools

git-tip

これらのTIPSを実際に試すことができるnpmパッケージ。
Dockerコンテナはこちら

以下はgit2.7.4で動作確認してるよ。

Everyday Git in twenty commands or so

git公式の使用サンプルを見る。

    git help everyday

Show helpful guides that come with Git

git公式にデフォルトで付いてくるサンプルガイドの一覧を見る。

    git help -g

Search change by content

コミットメッセージからコミットを検索する。

    git log -S'<a term in the source>'

となってるけど検索に引っかからなかったり余計なものが出たりしてよくわからん。

Sync with remote, overwrite local changes

ローカルの変更を捨て、リモートのブランチと同期する。

    git fetch origin && git reset --hard origin/master && git clean -f -d

List of all files till a commit

そのコミット時点で管理されている全ファイルを表示する。

    git ls-tree --name-only -r <commit-ish>

Git reset first commit

初回コミットを取り消す。
初回コミットはresetできないので特別な方法を行う必要がある。

    git update-ref -d HEAD

List all the conflicted files

コンフリクトしたファイルだけを表示する。

    git diff --name-only --diff-filter=U

List of all files changed in a commit

そのコミットで変更されたファイルの一覧を表示する。

    git diff-tree --no-commit-id --name-only -r <commit-ish>

Unstaged changes since last commit

最終コミットから変更されていてaddされていないソースを表示する。

    git diff

Changes staged for commit

最終コミットから変更されていてaddされているソースを表示する。

    git diff --cached
    git diff --staged

Show both staged and unstaged changes

最終コミットから変更されているソースを、add状態を問わず全てを表示する。

    git diff HEAD

List all branches that are already merged into master

ローカルにあるブランチのうち、既にmasterにマージ済のものを表示する。

    git branch --merged master

Quickly switch to the previous branch

checkoutする前にいたブランチに移動する。
cd -と同じようなもの。

    git checkout -
    git checkout @{-1}

Remove branches that have already been merged with master

既にmasterにマージされているブランチを一括削除する。

    git branch --merged master | grep -v '^\*' | xargs -n 1 git branch -d
    git branch --merged master | grep -v '^\*\|  master' | xargs -n 1 git branch -d

List all branches and their upstreams, as well as last commit on branch

ローカルブランチがどのリモートブランチに対応しているかと、リモートとの差分を表示する。

    git branch -vv

Track upstream branch

どのリモートブランチを追跡するかを選択する。

    git branch -u origin/mybranch

Delete local branch

ローカルブランチを削除する。

    git branch -d <local_branchname>

Delete remote branch

リモートブランチを削除する。

    git push origin --delete <remote_branchname>
    git push origin :<remote_branchname>

Delete local tag

ローカルタグを削除する。

    git tag -d <tag-name>

Delete remote tag

リモートタグを削除する。

    git push origin :refs/tags/<tag-name>

Undo local changes with the last content in head

ローカルで変更したファイルをHEADまで戻す。

    git checkout -- <file_name>

Revert: Undo a commit by creating a new commit

正反対のコミットを作ることで、元のコミットを取り消す。

    git revert <commit-ish>

Reset: Discard commits, advised for private branch

HEADを指定したコミットまで戻す。
通常はローカルブランチだけに行うこと。

    git reset <commit-ish>

Reword the previous commit message

直前のコミットをやりなおす。

    git commit -v --amend

See commit history for just the current branch

masterから現地点までのコミット履歴を一覧表示する。

    git cherry -v master

Amend author.

直前のコミットの実行者を変更する。

    git commit --amend --author='Author Name <email@address.com>'

Reset author, after author has been changed in the global config.

直前のコミットの実行者をデフォルト値にリセットする。

    git commit --amend --reset-author --no-edit

Changing a remote's URL

リモートブランチのURLを変更する。

    git remote set-url origin <URL>

Get list of all remote references

現在設定されている全てのリモートブランチを一覧表示する。

    git remote
    git remote show

Get list of all local and remote branches

ローカルとリモートの全部ランチを表示する。

    git branch -a

Get only remote branches

リモートのブランチを表示する。

    git branch -r

Stage parts of a changed file, instead of the entire file

ファイル全体ではなく、ファイル中の一部変更点だけをaddする。

    git add -p

Get git bash completion

gitの補完機能をインストールする。

    curl http://git.io/vfhol > ~/.git-completion.bash && echo '[ -f ~/.git-completion.bash ] && . ~/.git-completion.bash' >> ~/.bashrc

What changed since two weeks?

直近2週間の変更点だけを表示する。

    git log --no-merges --raw --since='2 weeks ago'
    git whatchanged --since='2 weeks ago'

See all commits made since forking from master

masterからforkしたところより後のコミット履歴を見る。

    git log --no-merges --stat --reverse master..

Pick commits across branches using cherry-pick

コミットを別のブランチにcherry-pickする。

    git checkout <branch-name> && git cherry-pick <commit-ish>

Find out branches containing commit-hash

指定のコミットが含まれているブランチを一覧表示する。

    git branch -a --contains <commit-ish>
    git branch --contains <commit-ish>

Git Aliases

グローバルなエイリアスを作成する。
下の例ならgit stgit statusになる。

    git config --global alias.<handle> <command>
    git config --global alias.st status

Saving current state of tracked files without commiting

前回コミットからの変更点を一時保存する。

    git stash
    git stash save

Saving current state of unstaged changes to tracked files

前回コミットからの変更点のうち、まだaddされていない部分だけを一時保存する。

    git stash -k
    git stash --keep-index
    git stash save --keep-index

Saving current state including untracked files

まだgit管理に入っていないファイルもstashする。

    git stash -u
    git stash save -u
    git stash save --include-untracked

Saving current state with message

任意のメッセージを付けてstashする。

    git stash save <message>

Saving current state of all files (ignored, untracked, and tracked)

前回コミットからの変更点を、ignoreしているファイルも含め全て一時保存する。

    git stash -a
    git stash --all
    git stash save --all

Show list of all saved stashes

現在登録されているstashの一覧を見る。

    git stash list

Apply any stash without deleting from the stashed list

stashリストから削除せずに変更を適用する。

    git stash apply <stash@{n}>

Apply last stashed state and delete it from stashed list

最後のstashを取り出して適用する。
popなので取り出したstashは消える。

    git stash pop
    git stash apply stash@{0} && git stash drop stash@{0}

Delete all stored stashes

stashを全て削除する。

    git stash clear
    git stash drop <stash@{n}>

Grab a single file from a stash

stashから1ファイルだけ取り出す。

    git checkout <stash@{n}> -- <file_path>
    git checkout stash@{0} -- <file_path>

Show all tracked files

現在git管理しているファイルを全て表示する。

    git ls-files -t

Show all untracked files

現在git管理していないファイルを全て表示する。

    git ls-files --others

Show all ignored files

現在gitignoreで無視しているファイルを全て表示する。

    git ls-files --others -i --exclude-standard

Create new working tree from a repository (git 2.5)

ワーキングツリーを作成する。
Gitのバージョン2.5以上で使用可能。

    git worktree add -b <branch-name> <path> <start-point>

Create new working tree from HEAD state

現在のHEADからワーキングツリーを作成する。

    git worktree add --detach <path> HEAD

Untrack files without deleting

ファイルをGit管理下から外す。ファイル自体は削除しない。

    git rm --cached <file_path>
    git rm --cached -r <directory_path>

Before deleting untracked files/directory, do a dry run to get the list of these files/directories

git cleanしたときに何が削除されるかをdry runで確認する。

    git clean -n

Forcefully remove untracked files

git管理下にないファイルを全削除する。

    git clean -f

Forcefully remove untracked directory

git管理下にないディレクトリを全削除する。

    git clean -f -d
    git clean -df

Update all the submodules

全てのサブモジュールをpullする。

    git submodule foreach git pull
    git submodule update --init --recursive
    git submodule update --remote

Show all commits in the current branch yet to be merged to master

現在のブランチ内で、まだmasterにマージされていないコミットを全て表示する。

    git cherry -v master
    git cherry -v master <branch-to-be-merged>

Rename a branch

ブランチ名を変更する

    git branch -m <new-branch-name>
    git branch -m [<old-branch-name>] <new-branch-name>

Rebases 'feature' to 'master' and merges it in to master

featureブランチをmasterにrebaseして、その後masterにマージする。

    git rebase master feature && git checkout master && git merge -

Archive the master branch

masterブランチをzipにする。

    git archive master --format=zip --output=master.zip

Modify previous commit without modifying the commit message

直前のコミット以降の変更を直前のコミットにまとめてひとつのコミットにする。コミットメッセージは変更しない。

    git add --all && git commit --amend --no-edit

Prunes references to remote branches that have been deleted in the remote.

リモートで既に削除されているブランチを手元に反映する。

    git fetch -p
    git remote prune origin

Retrieve the commit hash of the initial revision.

一番最初のコミットのハッシュを得る。

    git rev-list --reverse HEAD | head -1
    git rev-list --max-parents=0 HEAD
    git log --pretty=oneline | tail -1 | cut -c 1-40
    git log --pretty=oneline --reverse | head -1 | cut -c 1-40

Visualize the version tree.

コミットツリーを表示する。

    git log --pretty=oneline --graph --decorate --all
    gitk --all

Deploying git tracked subfolder to gh-pages

指定したサブツリーだけをoriginにpushする。

    git subtree push --prefix subfolder_name origin gh-pages

Adding a project to repo using subtree

サブツリーを現在のリポジトリに追加する。サブツリーの履歴は継承しない。

    git subtree add --prefix=<directory_name>/<project_name> --squash git@github.com:<username>/<project_name>.git master

Get latest changes in your repo for a linked project using subtree

指定したサブツリーだけをpullする。

    git subtree pull --prefix=<directory_name>/<project_name> --squash git@github.com:<username>/<project_name>.git master

Export a branch with history to a file.

指定したブランチをバンドルファイルに出力する。
インターネット接続できないところにリポジトリを再現したいときなどに使う。

    git bundle create <file> <branch-name>

Import from a bundle

上記で出力したバンドルファイルからcloneする。

    git clone repo.bundle <repo-dir> -b <branch-name>

Get the name of current branch.

現在のブランチ名を表示する。

    git rev-parse --abbrev-ref HEAD

Ignore one file on commit (e.g. Changelog).

コミット時に特定の1ファイルだけ無視する。
下の例ではChangelogを無視。

    git update-index --assume-unchanged Changelog; git commit -a; git update-index --no-assume-unchanged Changelog

Stash changes before rebasing

stashしてからrebaseする。

    git rebase --autostash

Fetch pull request by ID to a local branch

プルリクをID指定でローカルに持ってくる。

    git fetch origin pull/<id>/head:<branch-name>
    git pull origin pull/<id>/head:<branch-name>

Show the most recent tag on the current branch.

現在のブランチの一番直近のタグを表示する。

    git describe --tags --abbrev=0

Show inline word diff.

行単位ではなく単語単位でdiffを見る。

    git diff --word-diff

Show changes using common diff tools.

指定したdiffツールでgit diffを確認できる。

    git difftool -t <commit1> <commit2> <path>

Don’t consider changes for tracked file.

指定したファイルの変更を一時的に無視するようになる。

    git update-index --assume-unchanged <file_name>

Undo assume-unchanged.

無視していたファイルをgit管理下に戻す。

    git update-index --no-assume-unchanged <file_name>

Clean the files from .gitignore.

.gitignoreで無視しているファイルを全削除する。

    git clean -X -f

Restore deleted file.

削除したファイルを元に戻す。
一度もコミットしたことがないファイルは当然戻せない。

    git checkout <deleting_commit>^ -- <file_path>

Restore file to a specific commit-hash

指定のファイルを特定コミットのバージョンに戻す。

    git checkout <commit-ish> -- <file_path>

Always rebase instead of merge on pull.

pullしたときにmergeではなくrebaseするようにする。

    git config --global pull.rebase true
    git config --global branch.autosetuprebase always

List all the alias and configs.

全てのコンフィグとエイリアスの一覧を見る。

    git config --list

Make git case sensitive.

ファイル名の大文字小文字変更はデフォルトでは無視されるが、それを検知するようにする。

    git config --global core.ignorecase false

Add custom editors.

コミット時などに使用するエディタをViではなく他のものに変更する。

    git config --global core.editor '$EDITOR'

Auto correct typos.

コマンドを打ち間違ったときに正しいコマンドを推測して実行する。
設定はお勧めできない。

    git config --global help.autocorrect 1

Check if the change was a part of a release.

指定のハッシュが、どのブランチにいるかを表示する。

    git name-rev --name-only <SHA-1>

Dry run. (any command that supports dry-run flag should do.)

ドライラン。実際に実行はせず実行結果がどうなるかを表示する。
多くのコマンドがサポートしている。

    git clean -fd --dry-run

Marks your commit as a fix of a previous commit.

今回のコミットを、過去のコミットの修正としてマークする。
そのままでは特に何も起こらない

    git commit --fixup <SHA-1>

Squash fixup commits normal commits.

rebase時に上記のコミット順を隣に並べ替えてわかりやすくする。

    git rebase -i --autosquash
* 1111111 Xを実装した。
* 2222222 Yを実装した。
* 3333333 fixup! 1111111 Xのtypoを修正。
* 4444444 Zを実装した。

 ↓ rebase

* 1111111 Xを実装した。
* 3333333 fixup! 1111111 Xのtypoを修正。
* 2222222 Yを実装した。
* 4444444 Zを実装した。

Skip staging area during commit.

既にaddしているファイルは無視して、引数で与えたファイルだけをコミットする。

    git commit --only <file_path>

Interactive staging.

addをインタラクティブに行う。

    git add -i

List ignored files.

現在gitが無視しているファイルを表示する。
カレントディレクトリだけ。

    git check-ignore *

Status of ignored files.

現在gitが無視しているファイルを表示する。
update-indexで無視するようにしたファイルは表示されないっぽい。

    git status --ignored

Commits in Branch1 that are not in Branch2

Branch1には入っていて、Branch2に入っていないコミットを表示する。

    git log Branch1 ^Branch2

List n last commits

直近n個のコミットログを表示する。

    git log -<n>
    git log -n <n>

Reuse recorded resolution, record and reuse previous conflicts resolutions.

コンフリクトの解決法を記録しておき、今後同じ理由でのコンフリクトが見つかったら同じ方法で自動的に解決する。

    git config --global rerere.enabled 1

Open all conflicted files in an editor.

コンフリクトしたファイルを全てエディタに投げる。

    git diff --name-only | uniq | xargs $EDITOR

Count unpacked number of objects and their disk consumption.

現在のプロジェクトが使用しているオブジェクト数とディスク使用量を表示する。

    git count-objects --human-readable

Prune all unreachable objects from the object database.

到達不能オブジェクトを削除する。

    git gc --prune=now --aggressive

Instantly browse your working repository in gitweb.

一時的にブラウザから閲覧できるGitサーバを立ち上げる。

    git instaweb [--local] [--httpd=<httpd>] [--port=<port>] [--browser=<browser>]

View the GPG signatures in the commit log

署名付きコミットがあれば署名も表示する。

    git log --show-signature

Remove entry in the global config.

グローバル設定を削除する。

    git config --global --unset <entry-name>

Checkout a new branch without any history

これまでのコミットツリーとは無縁の新らしい空ブランチを作成する。

    git checkout --orphan <branch_name>

Extract file from another branch.

別ブランチのファイルを閲覧する。

    git show <branch_name>:<file_name>

List only the root and merge commits.

ファーストコミットのみ表示。
ブランチが入り乱れている場合に、メインブランチの履歴だけを表示する。
Git-flowに従っていればマージコミットとHotfixしか出なくなる。

    git log --first-parent

Change previous two commits with an interactive rebase.

直前の2コミットをインタラクティブにrebaseする。

    git rebase --interactive HEAD~2

List all branch is WIP

masterにマージされていないブランチを表示する。

    git checkout master && git branch --no-merged

Find guilty with binary search

二分探索でバグの発生したコミットを調査する。

    git bisect start                    # 開始
    git bisect bad                      # 最新コミットをbadにする
    git bisect good v2.6.13-rc2         # 問題なかったころのコミットのハッシュかタグをgoodにする
    git bisect bad                      # 適当に中間コミットがチェックアウトされるので
    git bisect good                     # テストを走らせてgood/badを指定すると、いずれ問題のコミットに突き当たる
    git bisect reset                    # 終了

Bypass pre-commit and commit-msg githooks

pre-commitフックが仕掛けられているときに、チェックをスルーしてコミットする。

    git commit --no-verify

List commits and changes to a specific file (even through renaming)

特定のファイルに対して、変更の履歴を表示する。

    git log --follow -p -- <file_path>

Clone a single branch

特定のブランチしかリモートを追跡しなくなる。

    git clone -b <branch-name> --single-branch https://github.com/user/repo.git

Create and switch new branch

現在のブランチから新しいブランチを作ってチェックアウトする。

    git checkout -b <branch-name>
    git branch <branch-name> && git checkout <branch-name>

Ignore file mode changes on commits

パーミッションの変更を追跡しなくなる。

    git config core.fileMode false

Turn off git colored terminal output

出力に色を付けなくする。

    git config --global color.ui false

Specific color settings

出力時の色設定を個別に変更する。

    git config --global <specific command e.g branch, diff> <true, false or always>

Show all local branches ordered by recent commits

ローカルブランチを最終コミットの新しい順に表示する。

    git for-each-ref --sort=-committerdate --format='%(refname:short)' refs/heads/

Find lines matching the pattern (regex or string) in tracked files

指定の文字列か正規表現でリポジトリを検索する。
出力はファイル毎にまとめて、行番号を表示する。

    git grep --heading --line-number 'foo bar'

Clone a shallow copy of a repository

cloneするときに最新のリポジトリだけ持ってくる。
非常に歴史の長いプロジェクトなどをcloneする際に有効。

    git clone https://github.com/user/repo.git --depth 1

Search Commit log across all branches for given text

コミットログを検索する。

    git log --all --grep='<given-text>'

Get first commit in a branch (from master)

masterから指定のブランチに向けての最初のコミットを表示する。

    git log master..<branch-name> --oneline | tail -1

Unstaging Staged file

addしたファイルをaddする前に戻す。

    git reset HEAD <file-name>

Force push to Remote Repository

リモートに強制的にpushする。
履歴が壊れるので、複数人で使用するブランチに対して使ってはいけない。

    git push -f <remote-name> <branch-name>

Adding Remote name

リモートリポジトリを追加する。

    git remote add <remote-nickname> <remote-url>

Show the author, time and last revision made to each line of a given file

ファイルの全行に対して、最終更新日と誰が更新したかを表示する。

    git blame <file-name>

Group commits by authors and title

ユーザ毎のコミット回数とメッセージを一覧表示する。

    git shortlog

Forced push but still ensure you don't overwrite other's work

リモートに強制的にアップするが、既に誰かがpushしていた場合はpushしない。
-fはやめてこっちを使った方が安全。

    git push --force-with-lease <remote-name> <branch-name>

Show how many lines does an author contribute

ユーザが貢献した行数を表示する。

    git log --author='_Your_Name_Here_' --pretty=tformat: --numstat | gawk '{ add += <!-- @doxie.inject start -->; subs += <!-- @doxie.inject end -->; loc += <!-- @doxie.inject start --> - <!-- @doxie.inject end --> } END { printf "added lines: %s removed lines: %s total lines: %s", add, subs, loc }' -
    git log --author='_Your_Name_Here_' --pretty=tformat: --numstat | awk '{ add += <!-- @doxie.inject start -->; subs += <!-- @doxie.inject end -->; loc += <!-- @doxie.inject start --> - <!-- @doxie.inject end --> } END { printf "added lines: %s, removed lines: %s, total lines: %s", add, subs, loc }' -

と書いてあるがシンタックスエラーになる。
プルリクに修正案が書いてあった。
git log --oneline --max-count=1 --date=short --pretty="%C(auto)%h %C(auto)%ad %C(auto)%C(auto)|%d %s %C(cyan)[%cn]" --author "$(git config --global user.email)"

Revert: Reverting an entire merge

マージコミットを取り消す。
コミットを削除するのではなく、ちょうどマージを打ち消すようなコミットを追加する。

    git revert -m 1 <commit-ish>

Number of commits in a branch

そのブランチに今まで何回のコミットがあったかを表示する。

    git rev-list --count <branch-name>

Alias: git undo

git undoが使えるようになる。

    git config --global alias.undo '!f() { git reset --hard $(git rev-parse --abbrev-ref HEAD)@{${1-1}}; }; f'

Add object notes

既存のコミットログは変更せずに別途コメント(notes)を追加する。

    git notes add -m 'Note on the previous commit....'

Show all the git-notes

全てのnotesを表示する。

    git log --show-notes='*'

Apply commit from another repository

別のリポジトリからコミットする。

    git --git-dir=<source-dir>/.git format-patch -k -1 --stdout <SHA1> | git am -3 -k

Specific fetch reference

特定のリモートブランチからfetchする。

    git fetch origin master:refs/remotes/origin/mymaster

Find common ancestor of two branches

2ブランチから共通の祖先を見付ける。

    diff -u <(git rev-list --first-parent BranchA) <(git rev-list --first-parent BranchB) | sed -ne 's/^ //p' | head -1

List unpushed git commits

pushしてないコミットを表示する。

    git log --branches --not --remotes
    git log @{u}..
    git cherry -v

Add everything, but whitespace changes

空白以外の変更をapplyする。

    git diff --ignore-all-space | git apply --cached

Edit [local/global] git config

ローカル/グローバルのgitコンフィグを編集する。

    git config [--global] --edit

blame on certain range

指定した行番号範囲内をblameする。

    git blame -L <start>,<end>

正しくはgit blame -L <start>,<end> <file-name>だと思われる。

Show a Git logical variable.

git変数を表示する。

    git var -l | <variable>

GIT_EDITORとかしか拾えない。

Preformatted patch file.

Git専用形式でパッチを作成する。

    git format-patch -M upstream..topic

Get the repo name.

リポジトリのルート絶対パスを取得する。

    git rev-parse --show-toplevel

logs between date range

日付指定でその間のログを表示する。

    git log --since='FEB 1 2017' --until='FEB 14 2017'

Exclude author from logs

指定者以外のログを表示する。

    git log --perl-regexp --author='^((?!excluded-author-regex).*)'

Generates a summary of pending changes

プルリクエストを送る。

    git request-pull v1.0 https://git.ko.xz/project master:for-linus

List references in a remote repository

リモートリポジトリのブランチを表示する。

    git ls-remote git://git.kernel.org/pub/scm/git/git.git

Backup untracked files.

git管理下に入ってないファイルをバックアップする。

    git ls-files --others -i --exclude-standard | xargs zip untracked.zip

List all git aliases

設定されているエイリアスを一覧表示する。

    git config -l | grep alias | sed 's/^alias\.//g'
    git config -l | grep alias | cut -d '.' -f 2

Show git status short

git statusを簡潔に表示する。

    git status --short --branch

Checkout a commit prior to a day ago

昨日のコミットをチェックアウトする。

    git checkout master@{yesterday}

と書いてあるが動かなかった。

Push a new local branch to remote repository and track

リモートにpushして追跡設定する。

    git push -u origin <branch_name>

感想

後半とかマニュアルのコピペじゃん的なものがあったりどう使うのかわからないものがあったり、もう少し厳選してほしいと思った。

144
163
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
144
163