Advanced Git

Remove last commit but keep changes unstaged

git reset HEAD^  

Blame Line(s) of Code on Someone

git blame -L20,+11 <file>  

How to tag an older commit in Git?

git tag -a v1.2 9fceb02 -m "Message here"  
# Where 9fceb02 is the beginning part of the commit id.
# You can then push them up using git push --tags origin master

Clone a specific Git branch

git clone -b <branch> <remote_repo>  

Stash latest commits in new branch then roll back

git branch newbranch

# Go back 3 commits. You *will* lose uncommitted work.*1
git reset --hard HEAD~3  
git push -f  

Clear files from git cache incase your .gitignore is acting up

# Make sure you save this file elsewhere it will be deleted!!!
git rm -r --cached somefile.json  

Rebase last N commits

# Interactive mode make sure EDITOR=vim

# N is the number of commits before HEAD
git rebase -i HEAD~N

# Use the commit number right before the commit you want the rebase to start at
git rebase -i <commit-number>  

Rebase vs Squash

# Both produce a "squashed" commit but they serve different purposes
git rebase --interactive  
git merge --squash  

Reset or revert a specific file to a specific revision

# Reverts to commit #abcde
git checkout abcde file/to/restore

# Reverts to HEAD
git checkout -- file/to/restore  

Fetch remote branch

git fetch <remote> <rbranch>:<lbranch>  
git checkout <lbranch>  

Delete remote branch

git push origin --delete <branchName>  
# OR
git push origin :<branchName>  

Step through changes to be staged

git add -p  

What do the all the options for "git add -p" do?

Stage this hunk [y,n,q,a,d,/,s,e,?]? ?  
y - stage this hunk  
n - do not stage this hunk  
q - quit; do not stage this hunk nor any of the remaining ones  
a - stage this hunk and all later hunks in the file  
d - do not stage this hunk nor any of the later hunks in the file  
g - select a hunk to go to  
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk  
J - leave this hunk undecided, see next hunk  
k - leave this hunk undecided, see previous undecided hunk  
K - leave this hunk undecided, see previous hunk  
s - split the current hunk into smaller hunks  
e - manually edit the current hunk  
? - print help

Diff name only

git diff --name-only file/one file/two  

Reset, Checkout, & Revert

git reset

git checkout

git revert  

Resources