~2 min read
Git: Cheat-sheet
If you find git confusing, here is a little cheat sheet! This includes my collection of all everyday use git commands, with explanations.
Basic Commands
- Git Config
1#set user name globally: 2git config --global user.name NAME 3 4#set user email globally 5git config --global user.email EMAIL 6 7#check saved info: 8git config user.name || git config user.email
- Creating repo
1#to create a git repository in the directory currently in: 2git init
- Staging
1#to check status, if staged or unstaged: 2git status 3 4#to add a file to the staging area: 5git add FILE_NAME 6 7#to remove a file from the staging area: 8git rm --cached FILE_NAME 9 10#to add all files in the project to the staging area: 11git add .
- Committing
1#to commit changes to the staging area (with a specific id): 2git commit -m "Added new changes" 3 4#shows all the commits with details: 5git log 6 7#shows all the commits in one line each: 8git log --oneline 9 10#awesome log: this will log the info in a nice format (Try it once 😉) 11git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
Go to the previous branch
1git checkout -
Get the history
1# Log in one line 2git log --oneline 3 4# Retrieve all commits by message 5# Here all commit that contain 'homepage' 6`git log --all --grep='homepage'` 7 8# Retrieve all commit by author 9git log --author="Maxence"
Reseted an unwanted commit. How to rollback?
1# Get everything you did 2git reflog 3 4# then reset to the desired commit (i.e. HEAD@{4}) 5git reset HEAD@{4} 6# ...or... 7git reset --hard <commit-sha1>
I mixed-up with my local repo. How to clean it?
1git fetch origin 2git checkout master 3git reset --hard origin/master 4# You're now up-to-date with master!
Difference between my branch and master
1git diff master..my-branch
Custom commits
1# Edit last commit 2git commit --amend -m "A better message" 3 4# Add something to the last commit 5# without writing message again 6git add . && git commit --amend --no-edit 7 8# empty commit - can be useful to re-trigger CI build... 9git commit --allow-empty -m "chore: re-trigger build"
Stash
Because it's not all about git stash
and git stash pop
1# save all tracked files 2git stash save "your message" 3 4# list your stashes 5git stash list 6 7# retrieve stash and delete 8git stash apply stash@{1} 9git stash drop stash@{1} 10# ... or in 1 command 11git stash pop stash@{1} 12
Clean branches
1# remove branches that no longer exist on remote 2git fetch -p 3 4# remove all branch that contains "greenkeeper" 5git fetch -p && git branch --remote | fgrep greenkeeper | sed 's/^.\{9\}//' | xargs git push origin --delete
Aliasing
Add a global aliase for git pull
1git config --global alias.pl pull
My favourite aliases
1alias g='git' 2alias glog='git log --oneline --decorate --graph' 3alias gst='git status' 4alias gp='git push' 5alias ga='git add' 6alias gc='git commit -v' 7