MaisTools
Developer/

Git Cheat Sheet

Quick Git reference: commands, flags, examples and variations organized by section with instant search.

Git Cheat Sheet

Commands, flags, examples and common errors

Config

git config

Reads or sets Git configuration options at three levels: system, user (global) or repository (local).

Flags--global--local--system--list--unset--edit
Example
git config --global user.name "John Doe"
git config --global user.email "john.doe@example.com"
git config credential.helper

Defines how Git stores HTTPS credentials so it doesn't ask for a password on every push.

Example
git config --global credential.helper manager
git config --global core.excludesfile

Sets a global .gitignore that applies to every repository.

Example
git config --global core.excludesfile ~/.gitignore_global

Repositories

git init

Creates a new Git repository in the current directory.

Flags--bare--initial-branch=--shared
Example
git init
git init --initial-branch=main meu-projeto
git clone

Copies a remote repository to the local machine, including the full history.

Flags--depth--branch--single-branch--recurse-submodules--mirror--bare
Example
git clone https://github.com/user/repo.git

Stage and commit

git status

Shows the state of the working directory and the staging area: what is modified, staged or untracked.

Flags-s-b--ignored-uno
Example
git status
git add

Moves changes from the working directory to the staging area, ready for the next commit.

Flags-A-p-i-u-n-f
Example
git add src/components/Button.tsx
git add .
git commit

Records the staged content as a new commit in the local repository with a message.

Flags-m-a--amend--no-edit-S--allow-empty--no-verify--fixup--squash
Example
git commit -m "feat: adiciona git cheat sheet"
git restore

Restores files: takes them out of staging or discards changes in the working directory.

Flags--staged--source=--worktree
Example
git restore --staged file.txt
git restore file.txt
git rm

Removes files from the repository (and optionally from disk).

Flags--cached-r-f-n
Example
git rm secret.env
git mv

Renames or moves a tracked file, equivalent to mv + git add + git rm.

Flags-f-n
Example
git mv old.tsx new.tsx

Branches

git branch

Lists, creates, renames or deletes branches.

Flags-a-r-vv-d-D-m-M--merged--no-merged--contains
Example
git branch
git branch feature/login
git checkout

Legacy command to switch branches or restore files. Today git switch and git restore are recommended.

Flags-b-B--orphan--detach
Example
git checkout main
git checkout -b feature/x
git switch

Modern replacement for checkout, dedicated to switching branches.

Flags-c-C--detach--discard-changes
Example
git switch main
git switch -c feature/login

Merge and rebase

git merge

Merges changes from another branch into the current one, creating a merge commit when needed.

Flags--no-ff--ff-only--squash--abort--continue-X-s
Example
git switch main
git merge feature/login
git rebase

Reapplies the commits of the current branch on top of another base, rewriting history.

Flags-i--onto--continue--abort--skip--autosquash--autostash
Example
git switch feature
git rebase main
git cherry-pick

Applies a specific commit from another branch onto the current one.

Flags-x-n--continue--abort
Example
git cherry-pick a1b2c3d
git mergetool

Opens a graphical tool to resolve merge conflicts.

Flags--tool=-y
Example
git mergetool --tool=meld

Remote

git remote

Manages the repository's remotes (origin, upstream, etc).

Subcommandsaddremoverenameset-urlshowprune
Flags-v
Example
git remote -v
git fetch

Downloads commits and refs from the remote without integrating them into the local branch.

Flags--all--prune--tags--depth--unshallow
Example
git fetch origin
git pull

Equivalent to git fetch followed by git merge (or rebase) on the current branch.

Flags--rebase--ff-only--no-rebase--autostash
Example
git pull origin main
git push

Sends local commits to the remote.

Flags-u--force--force-with-lease--tags--delete--dry-run--all
Example
git push -u origin feature/login

Stash

git stash

Saves uncommitted changes onto a temporary stack to clean the working directory.

Subcommandspush
Flags-u-a-m-k-p
Example
git stash push -m "WIP login"
git stash list / show / pop / apply / drop / clear

Manipulating the stash stack.

Example
git stash list
git stash pop

Tags

git tag

Creates, lists, deletes or verifies tags. Tags mark points in history (releases).

Flags-a-m-s-d-l-f
Example
git tag -a v1.2.0 -m "Release 1.2"
git describe

Returns a readable name based on the closest tag.

Flags--tags--always--dirty--abbrev
Example
git describe --tags --always --dirty

Log

git log

Shows the commit history with flexible filters and formatting.

Flags--oneline--graph--all--decorate-p--stat--since--author--grep-S
Example
git log --oneline --graph --decorate --all
git show

Shows the contents of a commit, tag or object.

Flags--stat--name-only--name-status
Example
git show HEAD
git show a1b2c3d:src/file.tsx
git diff

Shows differences between working dir, staging, commits or branches.

Flags--cached--staged--stat--name-only--word-diff
Example
git diff
git diff --cached
git diff main feature
git blame

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

Flags-L-w-C-M
Example
git blame -L 10,30 file.tsx
git shortlog

Summary grouped by author (useful for release notes).

Flags-s-n-e
Example
git shortlog -sne
git reflog

Local history of everything HEAD has touched. A lifesaver for recovering lost commits.

Subcommandsshowexpiredelete
Example
git reflog
git reset --hard HEAD@{2}

Undo

git reset

Moves HEAD to another commit, optionally altering staging and the working dir.

Flags--soft--mixed--hard--keep--merge
Example
git reset --soft HEAD~1
git reset --mixed HEAD~1
git reset --hard HEAD~1
git revert

Creates a new commit that undoes the changes of another. Safe on shared branches.

Flags--no-commit-m--continue--abort
Example
git revert a1b2c3d
git clean

Deletes untracked files from the working directory. Destructive operation.

Flags-n-f-d-x-X-i
Example
git clean -nfd

Submodules

git submodule add

Adds a repository as a submodule inside the current one.

Flags-b--name
Example
git submodule add -b main https://github.com/user/lib.git vendor/lib
git submodule init / update

Initializes and downloads submodules defined in .gitmodules.

Flags--init--recursive--remote--merge--rebase
Example
git submodule update --init --recursive
git submodule status / foreach / deinit

Inspect status, run a command in each submodule, or deactivate one.

Flags--recursive
Example
git submodule foreach 'git pull origin main'

Hooks

Activate a manual hook

Create an executable file under .git/hooks/ named after the event (pre-commit, pre-push, commit-msg, post-merge, etc).

Example
printf '#!/bin/sh\nnpm run lint\n' > .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
git config core.hooksPath

Defines a shared hooks directory (versionable, outside .git).

Example
git config core.hooksPath .githooks
Husky

JS tool that versions hooks in package.json and installs them automatically.

Example
npx husky init
echo "npm test" > .husky/pre-commit
git commit --no-verify

Skips the pre-commit and commit-msg hooks (use sparingly).

Example
git commit --no-verify -m "hotfix"

Advanced

git bisect

Binary search through history to find the commit that introduced a bug.

Subcommandsstartgoodbadskipresetrun
Example
git bisect start
git bisect bad HEAD
git bisect good v1.0
git bisect reset
git worktree

Creates multiple working directories tied to the same .git, allowing you to work on several branches in parallel.

Subcommandsaddlistremoveprune
Example
git worktree add ../proj-hotfix hotfix/urgente
git rebase -i

Rewrites history: combine, reorder, edit or drop commits.

Subcommandspickrewordeditsquashfixupdropexec
Example
git rebase -i HEAD~5
# pick    a1b2 feat: x
# squash  c3d4 fix typo
# reword  e5f6 chore: y
# drop    g7h8 wip
git filter-repo

Bulk history rewriter, modern replacement for git filter-branch. Useful to remove sensitive files.

Flags--path--invert-paths--replace-text
Example
git filter-repo --path secrets.env --invert-paths
git archive

Creates a tarball or zip of a ref's contents, without .git.

Flags--format--prefix-o
Example
git archive --format=zip --prefix=app/ -o release.zip v1.0
git bundle

Packs commits into a single file that can be transferred offline.

Subcommandscreateverifyunbundle
Example
git bundle create repo.bundle --all
git clone repo.bundle nova-pasta
git rev-parse

Resolves a reference into a full SHA, short SHA or name.

Flags--short--abbrev-ref--verify
Example
git rev-parse HEAD
git rev-parse --abbrev-ref HEAD
git rev-parse --short HEAD
git cat-file

Inspects Git objects (blobs, trees, commits, tags).

Flags-p-t-s
Example
git cat-file -p HEAD
git cat-file -t a1b2c3d
git ls-files / ls-tree

Lists tracked files (ls-files) or the contents of a tree (ls-tree).

Flags--cached--others--ignored
Example
git ls-files
git ls-tree -r HEAD --name-only
git gc / fsck

Maintenance: garbage collection, integrity checks, pruning loose objects.

Flags--aggressive--prune=now
Example
git gc --aggressive --prune=now
git fsck --full
git sparse-checkout

Lets you keep only a subset of the tree locally, useful for large monorepos.

Subcommandsinitsetlistdisable
Example
git sparse-checkout init --cone
git sparse-checkout set apps/web libs/ui
git notes

Adds notes to commits without changing their SHA.

Subcommandsaddshoweditremove
Example
git notes add -m "reviewed by QA" HEAD

Reference

Git workflow
┌──────────────┐  git add     ┌────────────┐  git commit  ┌─────────────┐  git push   ┌──────────┐
│ Working Dir  │ ───────────▶ │  Staging   │ ───────────▶ │ Local Repo  │ ──────────▶ │ Remote   │
│ (files)      │ ◀─────────── │  (index)   │ ◀─────────── │  (.git)     │ ◀────────── │ (origin) │
└──────────────┘  git restore └────────────┘  git reset   └─────────────┘  git fetch  └──────────┘
                                                                git pull = git fetch + git merge
  • untrackednew file, Git does not know it yet
  • modifiedknown file has been changed
  • stagedmarked for the next commit
  • committedsaved in .git, part of history
  • ignoredlisted in .gitignore
Merge vs Rebase vs Squash
Merge

Shared branches, integrating large features while preserving context, release branches.

Pros
  • Does not rewrite history
  • Safe in any scenario
  • Preserves the real timeline
Cons
  • History with diamonds and noise
  • Harder to read git log
Rebase

Updating a local feature branch against main before opening a PR. Keeping history linear.

Pros
  • Linear and clean history
  • Readable git log
  • More effective git bisect
Cons
  • Rewrites SHAs (NEVER on public branches)
  • Conflicts can be repetitive
  • Loses temporal context
Squash

Before merging a feature with multiple 'wip' or 'fix typo' commits into main.

Pros
  • 1 clean commit per feature
  • Ultra-readable history on main
Cons
  • Loses development granularity
  • git bisect only locates the whole feature

Golden rule: rebase locally, merge publicly. Never rebase branches others are using.

Reset: soft, mixed, hard
--softKeeps staging and working dir

Moves HEAD. Keeps staging and the working dir intact. Files remain staged.

Regroup commits without losing changes.

--mixedClears staging, keeps working dir

(default) Moves HEAD. Clears staging but keeps the working dir. Files become unstaged.

Redo what was going into the next commit.

--hardWipes everything (destructive)

Moves HEAD. Clears staging AND working dir. Wipes uncommitted changes. Destructive.

Return to the state of another commit, dropping everything.

Common errors and fixes
fatal: refusing to merge unrelated histories
Cause

The two repos do not share a common ancestor commit.

Solution

git pull origin main --allow-unrelated-histories

Updates were rejected because the remote contains work that you do not have
Cause

The remote has commits the local branch does not know about.

Solution

git pull --rebase origin main then git push. Never push --force without --force-with-lease.

Please commit your changes or stash them before you switch branches
Cause

There are local changes that would conflict when switching branches.

Solution

git stash, git switch other-branch, then git stash pop.

CONFLICT (content): Merge conflict in <file>
Cause

Merge or rebase touched the same lines as another branch.

Solution

Edit between <<<<<<< ======= >>>>>>> then git add file followed by git merge --continue. To abort: git merge --abort.

detached HEAD
Cause

Checked out a SHA or tag instead of a branch.

Solution

To keep the work: git switch -c new-branch. To discard: git switch main.

Permission denied (publickey)
Cause

SSH key not configured on GitHub or GitLab.

Solution

Run ssh-keygen -t ed25519 -C "email" and add ~/.ssh/id_ed25519.pub to the service's SSH keys.

fatal: Authentication failed (HTTPS)
Cause

GitHub no longer accepts passwords, you need a Personal Access Token.

Solution

Generate a PAT on GitHub and use it as the password, or switch the remote to SSH.

Your branch and 'origin/main' have diverged
Cause

Both sides have different commits.

Solution

git pull --rebase on a local feature, or plain git pull on a shared main.

error: failed to push some refs (non-fast-forward)
Cause

The remote moved on, you can't push without integrating first.

Solution

git pull --rebase then git push.

Deleted the wrong branch or did reset --hard and lost work
Cause

Destructive operation with no backup.

Solution

git reflog to find the SHA, then git checkout -b recovered <sha>. Commits stick around for ~30 days before gc.

.gitignore is not working
Cause

The file was already tracked before being ignored.

Solution

git rm --cached <file> then git commit -m "untrack". For directories: git rm -r --cached <folder>.

Committed a secret, password or .env file
Cause

Reckless git add . without checking what was staged.

Solution

Rotate the secret, run git filter-repo --path .env --invert-paths, git push --force-with-lease, and tell the team to reclone.

LF will be replaced by CRLF
Cause

Line ending differences between Windows and Unix.

Solution

git config --global core.autocrlf true on Windows, or input on Mac and Linux.

Filename too long (Windows)
Cause

Windows 260-character limit.

Solution

git config --system core.longpaths true