CodeNFacts
CodeHub
Home

All Categories


Sign In
git-cheatsheet

Git & GitHub Cheat Sheet

Every command, diagram, and hard-won lesson you actually reach for day to day - from your first git init to rescuing a branch you thought you broke.

safe / forward action branch / pull tag / caution destructive — read first

Mental model

The three (really four) trees

Almost every Git command just moves a change between these places. Once this clicks, the rest of Git is mostly vocabulary.

WorkingDirectoryyour edited filesStaging Area(Index)changes marked to commitLocalRepositorycommitted history (.git)Remote(GitHub)git addgit commitgit pushgit pull / fetch

Before you start

Setup & configuration

One-time-per-machine commands.

Identity & defaults

git config --global user.name "Your Name"

Sets the name attached to your commits.

git config --global user.email "you@example.com"

Sets the email attached to your commits — match your GitHub account email.

git config --global init.defaultBranch main

Makes new repos default to `main` instead of `master`.

git config --list

Shows all active config values and where they came from.

Starting a repository

git init

Turns the current folder into a new Git repository.

git clone <url>

Downloads a full copy of a remote repository, including history.

git clone <url> <folder>

Clones into a specific folder name instead of the repo's default.

git clone --depth 1 <url>

Shallow clone — only the latest commit, useful for huge repos.

Daily loop

Everyday commands

The status → add → commit loop you'll run dozens of times a day.

Check & review

git status

Shows staged, unstaged, and untracked changes.

git diff

Shows unstaged changes, line by line.

git diff --staged

Shows changes that are staged but not yet committed.

git show <commit>

Shows the full diff and metadata of a specific commit.

Stage & commit

git add <file>

Stages a specific file's changes.

git add .

Stages every change in the current directory.

git add -p

Interactively stage changes hunk by hunk — great for clean commits.

git commit -m "message"

Commits staged changes with a message.

git commit -am "message"

Stages every tracked file's changes and commits in one step.

Parallel work

Branching & merging

Branches are just movable pointers to commits — cheap to create, cheap to throw away.

Branching

git branch

Lists local branches.

git branch <name>

Creates a new branch (doesn't switch to it).

git switch <name>

Switches to an existing branch (modern replacement for checkout).

git switch -c <name>

Creates and switches to a new branch in one step.

git branch -d <name>

Deletes a branch that's already merged.

git branch -D <name>

Force-deletes a branch, merged or not.

Merging & rebasing

git merge <branch>

Merges another branch into the current one, keeping full history.

git rebase <branch>

Replays your commits on top of another branch — linear history.

git rebase -i HEAD~3

Interactive rebase: reorder, squash, or reword the last 3 commits.

git rebase --continue

Continues a rebase after resolving a conflict.

git rebase --abort

Bails out and restores the branch to before the rebase started.

Merge vs. rebase, in one line

Merge preserves exactly what happened (safe, a bit noisy). Rebase rewrites history to look linear (clean, but never do it on a branch someone else is also working on).

Syncing

Working with remotes

Your local repo talks to remotes (usually GitHub) with fetch, pull, and push.

Remotes

git remote -v

Lists remotes and their URLs.

git remote add origin <url>

Connects the local repo to a remote named 'origin'.

git fetch

Downloads remote changes without merging them into your branch.

git fetch --all --prune

Fetches all remotes and removes references to deleted remote branches.

Pull & push

git pull

Fetches and merges remote changes into your current branch.

git pull --rebase

Fetches and rebases your local commits on top — avoids merge clutter.

git push

Uploads your commits to the remote branch.

git push -u origin <branch>

Pushes and sets the remote as the branch's upstream, so future `git push` just works.

git push origin --delete <branch>

Deletes a branch on the remote.

Rescue

Undoing things

Mistakes are normal. Match the command to how far the change has traveled.

Safe undos

git restore <file>

Discards unstaged changes to a file, restoring it to the last commit.

git restore --staged <file>

Unstages a file without touching its contents.

git commit --amend

Edits the message (or adds staged changes to) the last commit.

git revert <commit>

Creates a new commit that undoes a previous one — safe on shared branches.

Rewriting history (careful)

git reset --soft HEAD~1

Undoes the last commit, keeps changes staged.

git reset --mixed HEAD~1

Undoes the last commit, keeps changes unstaged (default mode).

git reset --hard HEAD~1

Undoes the last commit and deletes the changes entirely. Only do this on commits nobody else has pulled.

git reflog

Shows a log of everywhere HEAD has pointed — your safety net after a bad reset.

Utilities

Stashing & tagging

Stash to shelve work-in-progress; tag to mark meaningful points like releases.

Stash

git stash

Shelves your uncommitted changes and cleans the working directory.

git stash -u

Also stashes untracked files.

git stash list

Lists all stashed sets of changes.

git stash pop

Re-applies the most recent stash and removes it from the stash list.

git stash apply

Re-applies a stash but keeps it in the list — useful across branches.

git stash drop

Deletes a stash without applying it.

Tags & history

git tag

Lists existing tags.

git tag v1.0.0

Creates a lightweight tag on the current commit.

git tag -a v1.0.0 -m "message"

Creates an annotated tag — preferred for releases.

git push origin --tags

Pushes all local tags to the remote.

git log --oneline --graph --all

A compact, visual view of branch and merge history.

git blame <file>

Shows who last changed each line of a file, and in which commit.

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

* 7e4f2a1 (HEAD -> main) Merge pull request #42
|\
| * 9c3d8b2 (feature/login) Add login validation
| * a1b2c3d Add login form
|/
* 5f6e7d8 Update README
* 3a2b1c0 Initial commit

Beyond Git

GitHub & pull requests

Git is the tool; GitHub is a hosting service and collaboration layer built on top of it.

Git

A version control tool that runs on your machine. Tracks history, branches, and diffs — works with no internet connection.

GitHub

A cloud service that hosts Git repositories and adds collaboration tools: pull requests, issues, code review, and CI/CD (Actions).

Fork & pull request flow

gh repo fork <owner>/<repo> --clone

Forks a repo to your account and clones it locally (GitHub CLI).

git remote add upstream <url>

Adds the original repo as a second remote so you can pull its updates.

git fetch upstream && git merge upstream/main

Syncs your fork with the original repo's latest changes.

gh pr create

Opens a pull request from your current branch.

gh pr list

Lists open pull requests in the repo.

gh pr checkout <number>

Checks out someone else's PR locally to review or test it.

Issues & repos (gh CLI)

gh repo clone <owner>/<repo>

Clones a repo using the GitHub CLI (handles auth for you).

gh issue create

Opens a new issue interactively.

gh issue list --assignee @me

Lists issues assigned to you.

gh pr view --web

Opens the current branch's PR in your browser.

gh run list

Lists recent GitHub Actions workflow runs.

Putting it together

A typical feature-branch workflow

Branch off main, commit as you go, open a PR, merge, tag a release.

mainfeature/loginmerge (PR #42)v1.2.0initialbranch point
  1. 1. git switch -c feature/login — branch off the latest main.
  2. 2. Commit in small, reviewable chunks as you build.
  3. 3. git push -u origin feature/login then gh pr create.
  4. 4. Address review comments with more commits, or an interactive rebase to tidy up.
  5. 5. Merge the PR, delete the branch, tag a release if it ships.

Habits that save you

Important things to keep in mind

Write commits in the imperative mood

"Add login validation," not "Added" or "Adds." It reads naturally next to git log and matches Git's own generated messages (e.g. "Merge branch...").

Never rewrite shared history

Once a commit is pushed and others may have pulled it, avoid rebase or reset --hard on that branch. Use git push --force-with-lease at most, and only on branches you own alone.

Set up .gitignore before your first commit

It's much easier to exclude node_modules/, .env, and build output from the start than to untrack them later with git rm -r --cached ..

Committed secrets don't just 'go away'

Deleting a secret in a new commit leaves it in history forever. Rotate the credential immediately, then use a tool like git filter-repo or the BFG Repo-Cleaner to scrub history.

Pull before you push

Running git pull (or --rebase) before pushing avoids most "non-fast-forward" rejections and surfaces conflicts early, while they're small.

A detached HEAD isn't broken

It just means you're not on a branch. If you've made commits you want to keep, run git switch -c new-branch-name before switching away.

Troubleshooting

Common mistakes & how to fix them

SituationFix
Committed to the wrong branchgit branch new-branch → git reset --hard HEAD~1 on the original → git switch new-branch
Need to change the last commit messagegit commit --amend
Merge conflict on a pullOpen the flagged files, resolve the <<<<<<< / ======= / >>>>>>> markers, then git add . && git commit
Accidentally deleted a branchgit reflog to find its last commit hash, then git branch <name> <hash>
A large or sensitive file got committedRemove with git filter-repo or BFG, then add the path to .gitignore
Force push overwrote a teammate's workThey can recover via their own git reflog; going forward use --force-with-lease and coordinate before force-pushing shared branches
Bookmark this page — git rewards muscle memory more than memorization.