Git Tips, Shortcuts and General Wisdom

Tricks

use git pull --rebase to make avoid polluting the history with merge messages on the main working branch

to make this a global setting use

git config branch.master.rebase true

for a specific repo, or

git config --global branch.master.rebase true

to make it a global setting for all repos

Logging

To find all the merges use this command

git log --grep="Merge"

which is more convenient than using git log | grep -E | less and does almost the same

Find deleted files

git log --diff-filter=D --summary | grep -i "filename"

can also use egrep instead of grep

Aliases

git config --global alias.s 'status -sb' short status

git config --global alias.amd 'commit --amend' git amend

git config --global alias.nb 'checkout -b' new branch

git config --global alias.db 'branch -d' delete branch

git config --global alias.br 'branch' branch shortcut

git config --global alias.lb 'branch -a' list all branches

My alias config:

[alias]
    co = checkout
    c = commit
    tag2id = !sh -c 'git rev-list $0 | head -n 1'
    status = status
    st = status -sb
    s = status -sb
    b = branch
    nb = checkout -b
    db = branch -d
    dB = branch -D                      # force delete branch
    lb = branch -a                      # list branches (all)
    br = branch
    amnd = commit --amend
    amd = commit --amend
    pl = pull --rebase=preserve
    pull-from = "!f() { git fetch $1 --prune; git merge --ff-only $1/$2 || git rebase --preserve-merges $1/$2; }; f"

Mini Scripts

Delete all local branches except master and release

git branch | egrep -v 'master|release' | xargs git branch -D

Advanced Git

Squash already pushed commits

  1. squash commits locally with git rebase -i origin/master~NUMBER master (NUMBER = # of commits to look back)
  2. force push with git push origin +master

Recover "lost" commits

If you have not run a gc yet and it has been less than 2 weeks (default gc setting) since the commits you lost were created you are in luck.

  1. run git fsck --lost-found to identify the dangling commits
  2. find commit you need git show GIT_HASH
  3. merge the commit to working branch git merge GIT_HASH