Git

Software · DevOps

Undo shit

# Undo last commit, keep changes staged
git reset --soft HEAD~1
 
# Undo last commit, keep changes unstaged
git reset HEAD~1
 
# Nuke last commit completely (DANGEROUS)
git reset --hard HEAD~1
 
# Undo a pushed commit (creates new commit)
git revert <commit-hash>
 
# Unstage a file
git reset HEAD <file>
 
# Discard changes to file
git checkout -- <file>
 
# I messed up, show me everything I did
git reflog

Branches

# New branch and switch to it
git checkout -b feature/thing
git switch -c feature/thing  # modern
 
# Delete local branch
git branch -d branch-name
git branch -D branch-name  # force
 
# Delete remote branch
git push origin --delete branch-name
 
# See all branches
git branch -a
 
# Track remote branch
git checkout --track origin/branch-name

Stash

# Stash changes
git stash
 
# Stash with message
git stash push -m "wip feature X"
 
# List stashes
git stash list
 
# Apply most recent (keep in list)
git stash apply
 
# Apply and remove from list
git stash pop
 
# Apply specific stash
git stash apply stash@{2}
 
# Drop a stash
git stash drop stash@{0}

Rebase

# Rebase onto main
git rebase main
 
# Interactive rebase last 3 commits
git rebase -i HEAD~3
 
# Abort
git rebase --abort
 
# Continue after fixing conflicts
git rebase --continue

Searching

# Search commit messages
git log --grep="bug fix"
 
# Search code changes
git log -S "function_name"
 
# Who wrote this line
git blame file.txt
 
# Find commit in all branches
git branch --contains <commit>

Misc

# Amend last commit message
git commit --amend -m "new message"
 
# Add forgotten file to last commit
git add forgotten_file
git commit --amend --no-edit
 
# Cherry pick
git cherry-pick <commit-hash>
 
# Clean untracked files
git clean -n  # dry run
git clean -f  # for real
 
# Diff between branches
git diff main..feature-branch
 
# Compact log
git log --oneline -20