Branching and Checkout:

  • Clean up local banches:
    1. git remote prune --dry-run origin
    2. 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

Diffing branches:

  • Log of commit on topic not on master: 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
  • 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”):
    1. git submodule deinit -f shared/
    2. rm -rf .git/modules/shared/
    3. 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:
    1. git tag TAG_NAME or git tag TAG_NAME BRANCH_OR_COMMIT_ID
    2. git push --tags

Bisecting:

  1. Start bisecting: git bisect start
  2. Mark known good and bad commits:
    • Good: git bisect good COMMIT_ID
    • Bad: git bisect bad COMMIT_ID
  3. Iterate, test, and give feedback: git bisect [ bad | good ]
  4. 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