Git tips and tricks

Create and switch new branch

1
git checkout -b <branch-name>

Find guilty with binary search

1
2
3
4
5
6
git bisect start             # Search start 
git bisect bad # Set point to bad commit
git bisect good v2.6.13-rc2 # Set point to good commit|tag
git bisect bad # Say current state is bad
git bisect good # Say current state is good
git bisect reset # Finish search

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

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

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

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

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

1
git branch -vv

List all git aliases

1
git config -l | grep alias | sed 's/^alias\.//g'

List ignored files

1
git check-ignore *

Prevent auto replacing LF with CRLF

1
git config --global core.autocrlf false

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

1
git fetch -p

Remove branches that have already been merged with master

1
2
git branch --merged master | grep -v '^\*\|  master' | xargs -n 1 git branch -d
# will not delete master if master is not checked out

See all commits made since forking from master

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

Show changes over time for specific file

1
git log -p <file_name>

Trace git remote commands

Add following environmental variables into your terminal.

1
2
3
export GIT_TRACE_PACKET=1
export GIT_TRACE=1
export GIT_CURL_VERBOSE=1

Visualize the version tree

1
git log --pretty=oneline --graph --decorate --all
  • You can save alias on the .gitconfig file to improve this
    1
    2
    3
    [alias]
    lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
    lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n'' %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all

What changed since two weeks?

  • Classic

    1
    git log --no-merges --raw --since='2 weeks ago'
  • New versions

    1
    git whatchanged --since='2 weeks ago'