git Cheat Sheet

Create new git branch

Create a new git branch and switch to it

git checkout -b <new branch name>

and create it on origin too

git push origin <new branch name>

Remove git branch

Remove git branch locally with

git branch -d <branch name>

and remove on origin too

git branch -d -r origin/
git push origin :

Alternatively remove on origin and then prune locally.

Remove stale git branches

When remote branches disappear clean them from your local repo with

git remote prune origin

Enable git password Caching

To keep passwords for 1h run

git config --global credential.helper 'cache --timeout=3600'

How to apply patches with git

A detailed description can be found here. You should always run the following commands:

git apply --stat cool_feature.patch    # Check what the patch will do
git apply --check cool_feature.patch   # Check if the patch fails
git am --signoff < cool_feature.patch

Git - Tracking Remote Branches

To follow additional branches in your local repo follow these steps:

# Find out all existing remote branches
git branch -r

# And track one of them locally
git branch --set-upstream-to <branch> <remote/branch>

Git and Stashing Changes

For a detailed explanation check here. This feature is useful to put debugging or experimental changes to the "background". Here are the commands:

git stash "Some test I made"    # Stash some changes away

git stash list                  # List stashes
git stash show stash@{0}        # Show changes file in last stash
git stash show -p stash@{0}     # Show patch for last stash

git stash apply stash@{0}       # Get last stash active again
git stash drop stash@{0}        # Delete last stash

git stash pop                   # Apply and remove last stash

git stash clear                 # Delete all stashes

# Stash just some files by adding all others first 
# and using --keep-index
git add <all files you want to keep>
git stash --keep-index

Remove all repo files from a directory

If you ever need to remove all git related files from a local working repo and make it just a normal directory:

git clean -ffrx

List Commits in One Line Each

git rev-list --all --pretty=oneline

List Git Branch in Bash Prompt PS1

There are several documentations online e.g. this one. In the end it boils down to running "git branch" on each prompt and to use an environment function __git_ps1() that is set up by "git branch" to print the branch if there is one. So if your current $PS1 is

export PS1='\u@\h:\w\$ "

you could extend it to

export PS1='\u@\h:\w$(git branch &>/dev/null; echo $(__git_ps1 "(%s)"))\$ '

to show the branch name in braces after the directory name and before the $ like this:

john@server:~/project/src(master)$