GIT Cheat Sheet

Setup

 

WhatHow
Add the current branch to your linux prompt and activate command completion.

1. Download and save the following script on your home directory as ".git-completion.sh". You can use any name, but these instructions assume you used the previous name.

 

https://github.com/git/git/blob/master/contrib/completion/git-completion.bash

 

2. Add the following to your ~/.bashrc file:

 

 

. ~/.git-completion.sh
export PS1='\[\033[00;37m\]\u@\h \W\[\033[01;32m\] [$(__git_ps1 "%s")]\[\033[00m\] \$ '
export GIT_PS1_SHOWDIRTYSTATE=true
export GIT_PS1_SHOWSTASHSTATE=true
export GIT_PS1_SHOWUNTRACKEDFILES=true
export GIT_PS1_SHOWUPSTREAM=auto

. ~/.git-completion.sh

export PS1='\[\033[00;37m\]\u@\h \W\[\033[01;32m\] [$(__git_ps1 "%s")]\[\033[00m\] \$ '

export GIT_PS1_SHOWDIRTYSTATE=true

export GIT_PS1_SHOWSTASHSTATE=true

export GIT_PS1_SHOWUNTRACKEDFILES=true

export GIT_PS1_SHOWUPSTREAM=auto

 

To know what each option above is used for and the meaning of the symbols that eventually show up near the branch name on the prompt, read the comments in the start of the script previously downloaded.
Configure useful aliases

$ git config --global alias.unstage 'reset HEAD --'

$ git config --global alias.last 'log -1 HEAD'

$ git config --global alias.undoall 'checkout -f'

 

To use the above aliases, just use the mnemonic after "alias.". Example, to know what the last commit was, type:

 

$ git last

Configure alias to open the JIRA ticket associated with the current branch

This is really a hack for my own machine, but you can use as an idea about what to do on yours. Since I name my topic branches with the corresponding JIRA ticket, I created an alias like this (I use chrome as my browser):

 

$ git config --global alias.ticket '!/opt/google/chrome/google-chrome https://issues.jboss.org/browse/$(git branch 2>/dev/null | grep "^\*" | cut -f 2- -d " ")'

 

Now, when I am working on a branch, lets say JBRULES-9999, and I want to open the corresponding jira, I just type:

 

$ git ticket

 

Daily Use

 

 

SubjectWhatHow
BranchesCreate a topic branch for work$ git checkout -b <branch_name> [<origin_branch>]
Undo all local changes

Be careful, as it literally deletes all local changes:

 

$ git checkout -f

Remove all untracked files (but not ignored files)$ git clean -d -f
Delete local topic branch$ git branch -d <branch_name>
Delete remote branch (BE CAREFUL)$ git push origin :<branch_name>
Rewind branch$ git reset --hard HEAD~<number_of_commits>
StashStash work$ git stash
Check stash stack$ git stash list
Reapply a stashed change, including updating the index$ git stash apply --index
Discard stashed work

$ git stash drop stash@{0}

 

where stash@{0} is the index of the element to drop in the stash stack.

CommitFix the latest commit$ git commit --amend
Remove last commit$ git reset --hard HEAD~1