GITHUB UNIVERSAL CHEATSHEET & TROUBLESHOOTING
A definitive, searchable index of core Git operations and solutions to common workflow issues. Filter by category, search errors, and copy clean snippets instantly.
Git Basics & Setup12 ENTRIES
Initialize a local Git repository in the current directory.
git init [directory-name]git init my-awesome-appRunning git init inside a folder that is already inside an existing Git repository, creating nested repository states.
Clone a remote repository to your local system.
git clone <url> [directory-name]git clone https://github.com/vercel/next.js.gitForgetting to cd into the newly cloned directory after cloning, and running commands in the parent folder.
Set repository or global configuration values like username and email.
git config --global user.name "Name"
git config --global user.email "email@domain.com"git config --global user.name "Jane Doe"
git config --global user.email "jane@example.com"Setting configurations locally in a directory not initialized as a git repository, or typing typos in emails leading to untracked GitHub stats.
Show the status of files in the working directory and staging area (tracked/untracked/modified).
git statusgit statusRelying on status blindly before committing without double checking the actual file diffs.
Add file changes in your working directory to the staging area.
git add <file-or-directory>
# Stage all changes:
git add .git add src/components/Header.tsx
git add .Staging secret credential files, environment files (.env), or node_modules accidentally using 'git add .'.
Record staged snapshots in version history.
git commit -m "<message>"git commit -m "feat: implement client-side regex tester"Writing generic commit messages like 'fix' or 'update' which make history hard to search, or committing without staging first.
Show commit logs/history of the active branch.
git log --oneline --graph --decorategit log --oneline -n 10Forgetting that git log shows history page-by-page and getting stuck inside the command pager (press 'q' to exit).
Show changes between commits, commit and working tree, or staged and unstaged states.
git diff [commit-hash]
# Show staged differences:
git diff --stagedgit diff HEAD~1
git diff --stagedRunning git diff without staging parameters and wondering why staged changes are not showing up.
Show various types of objects (commits, tags, files) with their content/diff metadata.
git show <commit-hash>:[filepath]git show a1b2c3d:src/App.tsxRunning git show without a commit hash when you want to view a past commit, which default shows only the latest commit.
Remove files from the working tree and index (stage).
git rm <filepath>
# Untrack file but keep it locally:
git rm --cached <filepath>git rm --cached .envRunning 'git rm <file>' without '--cached' when you want to keep the local copy; this will permanently delete the local file.
Move or rename a file, a directory, or a symlink.
git mv <source> <destination>git mv old-name.js new-name.jsRenaming files directly using your OS explorer; git treats it as deleted and untracked. Use git mv to preserve file history.
Display help information/manual pages for Git commands.
git help <command>git help rebaseSearching online manuals when git help runs the complete offline documentation instantly in your local browser.
Branching & Merging9 ENTRIES
Switch branches or restore working tree files.
git checkout <branch-name>
# Switch to past commit:
git checkout <commit-hash>git checkout feature/navbarSwitching branches with uncommitted modifications, which can cause conflict blockages.
Switch branches safely (a cleaner alternative to git checkout for branch navigation).
git switch <branch-name>
# Create and switch:
git switch -c <branch-name>git switch -c feat/analyticsForgetting that git switch only works for branches, not for viewing specific commits or file resets (use restore for files).
Restore working tree files from index or specific commits.
git restore <filepath>
# Unstage file changes:
git restore --staged <filepath>git restore --staged package-lock.jsonDiscarding modifications to working files; restored modifications cannot be recovered.
List, create, or delete branches.
git branch # list local
git branch -a # list local + remote
git branch -d <branch-name> # delete merged branch
git branch -D <branch-name> # force delete branchgit branch -D old-experimentTrying to delete the branch you are currently on. Switch to another branch first.
Merge target branch history into the active head branch.
git merge <branch-name>git merge mainMerging without running git pull first, leading to conflicts on outdated commits.
Reapply commits on top of another base tip. Keeps a clean linear history.
git rebase <base-branch>git rebase mainRebasing commits that have already been pushed to public/shared branches, rewriting history for other developers.
Apply the changes introduced by some existing commits onto the current branch.
git cherry-pick <commit-hash>git cherry-pick a1c3f9eCherry-picking commits without realizing they depend on changes introduced in prior commits, causing build failures.
Find as good common ancestors as possible for a merge.
git merge-base <branch-1> <branch-2>git merge-base feature mainUsing manual diff comparisons when merge-base identifies exactly where the branch diverged.
Summarize git log output, grouping commits by author.
git shortlog -s -ngit shortlog -s -nRunning shortlog without tags in huge repositories, resulting in spamming logs for thousands of commits.
Remotes & Collaboration9 ENTRIES
Manage set of tracked repositories (remotes).
git remote -v
git remote add <name> <url>
git remote remove <name>git remote add upstream https://github.com/org/repo.gitAdding duplicate remote names or typos in URLs, making it impossible to pull/push.
Download objects and refs from another repository. Does not modify local files.
git fetch <remote>git fetch originThinking git fetch updates your active working code. You must merge or rebase after fetching to sync.
Fetch from and integrate with another repository or local branch.
git pull <remote> <branch>git pull origin mainRunning git pull when you have dirty uncommitted local modifications, causing automatic merging to fail.
Update remote refs along with associated objects.
git push <remote> <branch>
# Set upstream tracking branch:
git push -u origin <branch>git push -u origin feature-xUsing push --force blindly on master/main branches, destroying other team members' code snapshots.
Delete stale tracking branches under <name> that no longer exist on the remote.
git remote prune <remote-name>git remote prune originExpecting local physical branches to be deleted. It only cleans obsolete remote-tracking markers (e.g. origin/feature-x).
Give information about a specific remote repository.
git remote show <remote-name>git remote show originRunning this offline; it requires active remote network communication to check branch sync states.
Clone repository containing all branch references, tags, and settings as a full mirror.
git clone --mirror <url>git clone --mirror https://github.com/user/project.gitCloning a mirror expecting a normal working tree; it contains only raw .git databases (bare repository).
Initialize, update, or inspect nested submodules inside a Git repository.
git submodule add <url> <path>
git submodule update --init --recursivegit submodule update --init --recursiveCloning a project containing submodules without running 'submodule update --init', leaving submodules empty.
Generate a summary of pending changes to ask upstream maintainers to pull.
git request-pull <start-commit> <url> [end-commit]git request-pull v1.0 https://github.com/my/repo mainSpecifying wrong range boundaries, causing unnecessary or unrelated changes to be requested.
Undoing & Fixing Errors8 ENTRIES
Undo the last commit(s), moving HEAD back, but keeping all changes staged in the index.
git reset --soft HEAD~<number-of-commits>git reset --soft HEAD~1Assuming changes are deleted. This command preserves all modified code in your staged index.
Undo commits and unstage changes, leaving files modified in working directory. This is the default reset mode.
git reset --mixed HEAD~1git reset HEAD~1Running this when you wanted to keep modifications staged. You will have to re-add changes to the stage.
Discard all uncommitted changes and revert to a specific commit. Warning: destructive operation!
git reset --hard <commit-hash>git reset --hard HEAD~1Executing reset --hard when you have valuable uncommitted modifications; they will be permanently lost.
Create a new commit that undoes the effects of previous commits without rewriting history.
git revert <commit-hash>git revert 8b3c9e1Reverting a commit that was already reverted, causing confusing logical code loops in history.
Show a record of all commits, branch switches, resets, and merges. Best tool to recover 'lost' commits.
git refloggit reflogAssuming deleted branches or hard resets are unrecoverable without checking reflog first.
Remove untracked files and directories from the working tree.
git clean -fd
# Dry run check first:
git clean -nfdgit clean -fdRunning clean without double-checking the files list via dry-run (-n), which permanently deletes local configuration files.
Replace the tip commit of the current branch with a new commit, allowing changes or rewrites to message.
git commit --amend -m "<new-message>"git commit --amend -m "docs: fix header typo"Amending a commit that has already been pushed to a shared remote, which will require force-pushing.
Discard local changes in the working directory (older equivalent to git restore).
git checkout -- <filepath>git checkout -- src/styles.cssConflating this branch-switching command syntax, which is why git restore is preferred in modern Git.
Stashing7 ENTRIES
Temporarily save (stash) changes in your dirty working directory so you can work on something else.
git stash save "<message>"
# Save with untracked files:
git stash -ugit stash save "layout edits WIP" -uStashing without keeping track of what was modified, then accumulating 30 stashes and forgetting which is which.
List stashed state changes.
git stash listgit stash listStashing changes and then forgetting about them, resulting in merge issues weeks later.
Remove the single most recently stashed state from the stash list and apply it to active branch.
git stash pop [stash-index]git stash pop stash@{0}Popping a stash on a branch different from where you created it, causing messy merge conflicts.
Apply stashed changes to active branch, but do not delete the stash from the stashing list.
git stash apply [stash-index]git stash apply stash@{1}Applying stash multiple times by mistake, creating duplicated merge conflict sections.
Remove a single stashed state from the stash list.
git stash drop <stash-index>git stash drop stash@{2}Dropping the wrong stash index because the indices shift after popping or dropping other items.
Remove all stashed states. Warning: irreversible action!
git stash cleargit stash clearClearing the entire stash pool when you wanted to delete a single stash index, resulting in lost stashed code.
Show the changes recorded in the stash as a diff.
git stash show -p [stash-index]git stash show -p stash@{0}Running stash show without '-p' when you want to view the actual file diffs (defaults to file stats summary).
Tagging & Releases5 ENTRIES
List tags in alphabetical order, or look up specific tags.
git tag
git tag -l "v1.2.*"git tag -l "v2.0.*"Forgetting that git tag only lists local tags unless updated via git fetch.
Create an annotated tag containing tagger metadata, date, and messages, GPG signed if specified.
git tag -a <tag-name> -m "<tag-message>"git tag -a v1.0.0 -m "Release v1.0.0 stable release version"Creating lightweight tags (without -a) for public releases, which omit tagger identification details.
Delete a local tag.
git tag -d <tag-name>git tag -d v1.0.0-rc1Deleting a local tag thinking it automatically deletes the tag on GitHub. Remote tags must be purged separately.
Push all local tags that are not yet on the remote server.
git push <remote> --tagsgit push origin --tagsRunning 'git push' without '--tags' when publishing releases; normal push commands do not transfer tags.
Delete a tag on the remote repository.
git push <remote-name> --delete <tag-name>
# Older syntax:
git push <remote-name> :refs/tags/<tag-name>git push origin --delete v1.0.0-betaLeaving a broken tag on remote repositories which causes conflict failures for other developers during fetch.
Advanced Utilities & Plumbing11 ENTRIES
Start an interactive rebase session to edit, squash, reword, or drop commits in history.
git rebase -i HEAD~<number-of-commits>git rebase -i HEAD~5Closing the text editor without realizing it initiates the rebase, or deleting commits accidentally from the pick list.
Manage multiple working trees attached to the same repository. Work on multiple branches in different folders simultaneously.
git worktree add <path> <branch>
git worktree list
git worktree remove <path>git worktree add ../debug-build hotfix/authModifying files inside a worktree thinking it is a separate repository, and forgetting to prune removed worktrees.
Use binary search to find the commit that introduced a bug.
git bisect start
git bisect bad # Current version has the bug
git bisect good <commit-hash> # Last known working version
# Type 'git bisect good' or 'git bisect bad' iteratively, then:
git bisect resetgit bisect start
git bisect bad
git bisect good v1.0.0Forgetting to run 'git bisect reset' after finding the bug, leaving the repository in a detached HEAD bisect state.
Show what revision and author last modified each line of a file.
git blame <filepath>git blame src/components/Header.tsxBlaming files that have been auto-formatted, which shows the formatter author instead of the logic author (use --ignore-revs-file if needed).
Create a zip or tar archive of the files in a repository from specific branches or commits.
git archive --format=<zip|tar> --output=<filename> <branch-name>git archive --format=zip --output=v1-source.zip mainArchiving repositories and expecting the .git history directory to be included; it only packs working directory code.
Run garbage collection to optimize database size, clean up unreachable commits, and compress history.
git gc --prune=nowgit gc --prune=nowPruning reflog commits that you might still want to restore. Use with caution!
Verify the connectivity and validity of objects in the database, checking for corrupted commits.
git fsck --fullgit fsck --fullRunning fsck and deleting loose objects without back-ups if corruption occurred.
Prepare commits for email submission, generating a series of .patch files.
git format-patch <start-commit-hash>..HEADgit format-patch v1.0.0..mainCreating format-patches in a folder where you have local uncommitted changes, making organization messy.
Apply a series of patches from a mailbox/local patch files.
git am < <patch-file>git am 0001-fix-layout-bug.patchApplying patches generated from an incompatible branch state, leading to patch conflict failures.
Package objects and references in an offline file. Useful for sharing code without remote servers.
git bundle create <filename> <branch-name>
# Clone from a bundle:
git clone <filename> -b <branch>git bundle create backup.bundle mainForgetting to specify references (branches/tags) when packaging, resulting in an empty bundle file.
Find the most recent tag reachable from a commit, suffixing it with commit counts and hashes.
git describe --tags --alwaysgit describe --tags --alwaysAssuming it works in a repository without any tags, which will fall back to returning only the commit hash.
Git Disasters & Solutions14 ENTRIES
You accidentally committed code directly to the 'main' branch instead of a dedicated feature branch.
# 1. Create a new branch pointing to current changes:
git branch feat/your-feature-name
# 2. Reset local main back one commit (or more):
git reset --hard HEAD~1
# 3. Switch to your feature branch:
git checkout feat/your-feature-namegit branch feat/search-bar
git reset --hard HEAD~1
git checkout feat/search-barPerforming this action if you already pushed main to GitHub. You will have to coordinate with your team to force-push.
You made a commit but immediately realized you made a typo or forgot to include a file, and want to redo it.
# Undo commit, keep files modified and staged:
git reset --soft HEAD~1
# Undo commit, keep files modified but unstaged:
git reset HEAD~1git reset --soft HEAD~1Using 'git reset --hard HEAD~1' instead, which will completely delete the changes you just made.
You accidentally ran 'git reset --hard' and lost all your uncommitted or committed work.
# 1. Run reflog to find the commit hash before the reset:
git reflog
# 2. Revert HEAD to that commit hash:
git reset --hard <commit-hash>git reflog
# Output showing: HEAD@{1}: reset: moving to HEAD~1
# HEAD@{2}: commit: feat: added sidebar
git reset --hard a2f3c9eRunning 'git clean -fd' or closing the workspace before fetching the hash from the log, or thinking uncommitted changes can be recovered this way (reflog only recovers committed changes).
You accidentally committed a file containing API keys, passwords, or secrets, and need to scrub it from all branch histories.
# Remove the file from all commits and rewrite history:
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch <filename>" \
--prune-empty --tag-name-filter cat -- --all
# Note: Force pushing is required afterwards:
git push origin --force --allgit filter-branch --force --index-filter "git rm --cached --ignore-unmatch .env" --prune-empty --tag-name-filter cat -- --allAssuming simple 'git rm file' deletes it from history. The keys will still be accessible in past commits unless history is rewritten.
You changed a filename's casing (e.g., header.tsx to Header.tsx), but Git doesn't detect the modification due to default config.
# Force rename via Git:
git mv <old-name> <new-name>
# Alternatively, disable core ignorecase:
git config core.ignorecase falsegit mv src/components/header.tsx src/components/Header.tsxRenaming the file directly in your OS Explorer or VS Code sidebar. Git will show duplicate untracked/deleted files.
You need to rename your active local branch and update the remote tracking branch accordingly.
# 1. Rename active branch locally:
git branch -m <new-name>
# 2. Push the new branch and set remote upstream:
git push origin -u <new-name>
# 3. Delete the old branch on the remote server:
git push origin --delete <old-name>git branch -m feat/search-ui
git push origin -u feat/search-ui
git push origin --delete feat/srch-uiRenaming a branch other developers are actively basing their pull requests on, breaking their target remotes.
You want to completely erase all local modifications (tracked and untracked) to start over from fresh pull state.
# 1. Reset all tracked files to current commit:
git reset --hard HEAD
# 2. Remove all untracked files and directories:
git clean -fdgit reset --hard HEAD && git clean -fdRunning 'git clean -fdx' if you want to keep files in your gitignore, like local .env files or configuration parameters.
You committed code but realized it has the wrong git author email or name.
# Update only the last commit:
git commit --amend --author="Name <email@example.com>"git commit --amend --author="John Doe <john@doe.com>"Amending a commit that you have already pushed to a shared remote, which requires force-pushing.
Your branch conflicts with another branch and Git halts the merge, inserting conflict markers.
# 1. Run status to list conflicting files:
git status
# 2. Open files, resolve markers (<<<<<<<, =======, >>>>>>>), then stage:
git add <resolved-file>
# 3. Complete the merge transaction:
git commit -m "merge: resolved conflicts with origin/main"git status
# resolve conflicts in files...
git add src/components/Header.tsx
git commit -m "merge: resolved conflicts"Running git commit before resolving all files, or committing code with raw conflict symbols (<<<<<<<) still left in files.
You merged a branch but realized it broke the project, and you want to completely rollback the merge commit.
# Revert a merge commit, specifying the mainline parent index (usually 1):
git revert -m 1 <merge-commit-hash>git revert -m 1 3c8e4a2Using normal git revert without the -m option, which causes git to throw an error since merge commits have multiple parents.
Your push is rejected because the remote contains commits you don't have locally.
# 1. Fetch remote updates and rebase your local commits on top:
git pull --rebase origin <branch-name>
# 2. Resolve conflicts if any, and continue rebase:
git rebase --continue
# 3. Safely push modifications:
git push origin <branch-name>git pull --rebase origin main && git push origin mainUsing 'git push --force' without checking remote differences, which will overwrite other developers' work permanently.
You deleted a branch locally using git branch -D and now want to restore it.
# 1. Find the tip commit hash of the deleted branch in reflog:
git reflog
# 2. Re-create the branch from that commit hash:
git branch <branch-name> <commit-hash>git reflog
# HEAD@{3}: checkout: moving from feature-auth to main
# HEAD@{4}: commit: feat: added bcrypt auth
git branch feature-auth a1c2b3dThinking deleted branches are gone forever, or running garbage collection (git gc) which purges dangling commit objects.
Git commands fail with 'Another git process seems to be running in this repository' error because of a stale lock file.
# Remove the stale index lock file manually:
rm -f .git/index.lockrm -f .git/index.lockDeleting files under the refs directory or deleting index itself, which corrupts version staging tables.
GitHub rejects your push because you committed a file exceeding the 100MB limit.
# 1. Remove large file from active index:
git rm --cached <path-to-large-file>
# 2. Rewrite history to remove files from past commits:
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch <path-to-large-file>" \
--prune-empty --tag-name-filter cat -- --all
# 3. Push history clean:
git push origin maingit rm --cached data/large_dataset.zip && git filter-branch --force --index-filter "git rm --cached --ignore-unmatch data/large_dataset.zip" --prune-empty --tag-name-filter cat -- --allDeleting the file locally and committing the delete; the file will still exist in historical commit objects, blocking pushes.