Branching and Checkout:
- Clean up local banches:
git remote prune --dry-run origin
git remote prune origin
- Update local branch without it being checked out:
git fetch origin src_branch:local_branch
- Show which remote branch local branches are tracking:
git branch -vv
- Display branches by last commit date:
git for-each-ref --sort=-committerdate refs/heads/
- Copy files/directories from another branch to current branch:
git checkout source_branch -- path/to/dir/ path/to/file.txt
- Reset to a particular commit without losing changes:
- Reset to one commit past most recent:
git reset HEAD^
- Reset to particular commit:
git reset COMMIT_ID
- Reset to one commit past most recent:
Diffing branches:
- Log of commit on
topic
not onmaster
:git log master..topic
- Diffs introduced by
topic
branch:git diff master...topic
Helpful page: https://matthew-brett.github.io/pydagogue/pain_in_dots.html
Deleting:
- Delete remote branch:
git push --delete origin BRANCH_NAME
Fixing Mistakes:
- Reset a local branch back to state of the remote branch:
git reset --hard origin/remote_branch
- Remove file from repository which has already been committed:
git rm --cached <filename>
- Cherry-pick a…
- …a single commit:
git cherry-pick COMMIT_ID
- …an inclusive range of commits:
git cherry-pick commitid1^..commitid2
- …a single commit:
- Create branch based on specific commit ID:
git checkout -b BRANCH_NAME COMMIT_ID
Viewing Diffs And Changes:
- View differences between commits:
git diff OLDER_COMMIT NEWER_COMMIT
- Diff branches:
git diff master..production
- Diff file between branches:
git diff master..production path/to/file
- Negative pathspec:
git diff ':^path/to/exclude/here'
Rebasing:
- Rebase up to a given commit (exclusive):
git rebase -i COMMIT_ID
- Rebase last 4 commits (inclusive):
git rebase -i HEAD~4
Submodules:
- Add a submodule:
git submodule add -b master git@GIT_HOST/REPO.git DIR_TO_CREATE_SUBMODULE_IN
- Remove a submodule (example submodule is named “shared”):
git submodule deinit -f shared/
rm -rf .git/modules/shared/
git rm -f shared/
Worktrees:
- Add:
git worktree add /tmp/worktree-dir branch_name
- Remove:
git worktree remove /tmp/worktree-dir
- Remove worktrees whose folders no longer exist:
git worktree prune
Tags:
- Create and push tag:
git tag TAG_NAME
orgit tag TAG_NAME BRANCH_OR_COMMIT_ID
git push --tags
Bisecting:
- Start bisecting:
git bisect start
- Mark known good and bad commits:
- Good:
git bisect good COMMIT_ID
- Bad:
git bisect bad COMMIT_ID
- Good:
- Iterate, test, and give feedback:
git bisect [ bad | good ]
- When done:
git bisect reset
Changing a remote:
- See current remote:
git remote -v
- Change remote:
git remote set-url origin new.git.url/here