Git Cheat Sheet

Cheet says: Version control is your friend!

Basics


Initialize a repo

git init

Clone a repo

git clone https://github.com/user/repo.git

Check status

git status

Add files

git add file.txt # Single file git add . # All files git add -p # Interactive (pick chunks)

Commit

git commit -m "message" git commit -am "message" # Add + commit tracked files

Push

git push origin main git push -u origin main # Set upstream

Branches


List branches

git branch # Local git branch -a # All (including remote)

Create branch

git branch feature-x git checkout -b feature-x # Create and switch

Switch branches

git checkout main git switch main # Modern way

Delete branch

git branch -d feature-x # Safe delete git branch -D feature-x # Force delete git push origin --delete feature-x # Delete remote

Merging & Rebasing


Merge

git checkout main git merge feature-x

Rebase (cleaner history)

git checkout feature-x git rebase main

Interactive rebase (squash commits)

git rebase -i HEAD~3

Undoing Things


Unstage file

git reset HEAD file.txt git restore --staged file.txt # Modern way

Discard changes

git checkout -- file.txt git restore file.txt # Modern way

Undo last commit (keep changes)

git reset --soft HEAD~1

Undo last commit (discard changes)

git reset --hard HEAD~1

Revert a commit (safe for shared branches)

git revert abc123

Stashing


Stash changes

git stash git stash push -m "description"

List stashes

git stash list

Apply stash

git stash pop # Apply and remove git stash apply # Apply and keep git stash apply stash@{2}

Drop stash

git stash drop stash@{0}

Viewing History


Log

git log git log --oneline git log --graph --oneline --all

Show commit

git show abc123

Diff

git diff # Working vs staged git diff --staged # Staged vs last commit git diff main..feature # Between branches

Remote Operations


Add remote

git remote add origin url

View remotes

git remote -v

Fetch (download without merge)

git fetch origin

Pull (fetch + merge)

git pull origin main

Push

git push origin main

Force push (careful!)

git push --force-with-lease # Safer than --force

Useful Aliases

Add to `~/.gitconfig`:

[alias]
    st = status
    co = checkout
    br = branch
    ci = commit
    lg = log --oneline --graph --all
    unstage = reset HEAD --
    last = log -1 HEAD

Pro Tips


See who changed what

git blame file.txt

Find when bug was introduced

git bisect start git bisect bad # Current is bad git bisect good abc123 # This commit was good

Clean untracked files

git clean -n # Dry run git clean -fd # Actually delete

Amend last commit message

git commit --amend -m "new message"