This cheatsheet provides a comprehensive, quick-reference guide to Git, covering essential commands, advanced operations, workflow best practices, and troubleshooting tips. It’s designed for developers needing fast, accurate information for real-world development scenarios as of December 2025.


Quick Reference: Most Used Commands

CommandDescriptionExample
git initInitializes a new Git repository.git init
git clone <url>Clones an existing repository.git clone https://github.com/user/repo.git
git add <file>Stages changes for the next commit.git add index.html
git add .Stages all changes in the current directory.git add .
git commit -m "msg"Records staged changes to the repository.git commit -m "Add header component"
git statusShows the working tree status.git status
git logDisplays commit history.git log --oneline --graph
git branchLists, creates, or deletes branches.git branch feature/new-feature
git checkout <branch>Switches to a specified branch.git checkout develop
git checkout -b <new-branch>Creates and switches to a new branch.git checkout -b bugfix/login-issue
git merge <branch>Integrates changes from one branch into another.git merge feature/new-feature
git push <remote> <branch>Uploads local branch commits to remote.git push origin main
git pull <remote> <branch>Fetches and integrates remote changes.git pull origin main
git remote -vLists configured remote repositories.git remote -v

Getting Started & Configuration

Setup

CommandDescriptionExample
git initInitializes a new Git repository in the current directory.git init
git clone <url>Clones an existing repository from a URL into a new directory.git clone https://github.com/octocat/Spoon-Knife.git

Basic Configuration

These settings are global unless --local is specified.

CommandDescriptionExample
git config --global user.name "Your Name"Sets the author name for all future commits.git config --global user.name "Alice Smith"
git config --global user.email "[email protected]"Sets the author email for all future commits.git config --global user.email "[email protected]"
git config --global core.editor "code --wait"Sets the default text editor for Git (e.g., VS Code).git config --global core.editor "code --wait"
git config --listLists all Git configurations.git config --list

Basic Commands

Staging and Committing

CommandDescriptionExample
git add <file>Stages specific file(s) for the next commit.git add src/main.js
git add .Stages all modified and new files in the current directory and subdirectories.git add .
git add -uStages only modified and deleted files (not new files).git add -u
git rm --cached <file>Unstages a file without deleting it from the working directory.git rm --cached config.txt
git commit -m "message"Records the staged changes with a descriptive message.git commit -m "Implement user authentication"
git commit --amendAmends the last commit (e.g., to change message or add forgotten files).git commit --amend --no-edit (amend without changing message)

Checking Status and History

CommandDescriptionExample
git statusShows the status of your working directory and staging area.git status
git diffShows changes between the working directory and the staging area.git diff
git diff --stagedShows changes between the staging area and the last commit.git diff --staged
git logDisplays the commit history.git log
git log --onelineShows a condensed, one-line view of the commit history.git log --oneline
git log --graph --oneline --decorateVisualizes branch and merge history with a graph.git log --graph --oneline --decorate
git log -p <file>Shows commit history with diffs for a specific file.git log -p src/App.js

Remote Operations

CommandDescriptionExample
git remote -vLists all configured remote repositories.git remote -v
git remote add <name> <url>Adds a new remote repository.git remote add upstream https://github.com/forked/repo.git
git fetch <remote>Downloads objects and refs from another repository.git fetch origin
git pull <remote> <branch>Fetches from and integrates with another repository or a local branch.git pull origin main
git push <remote> <branch>Uploads local branch commits to the remote repository.git push origin feature/login
git push -u <remote> <branch>Pushes and sets the upstream branch (first push).git push -u origin feature/login

Branching & Merging

Branch Management

CommandDescriptionExample
git branchLists all local branches.git branch
git branch -aLists all local and remote branches.git branch -a
git branch <new-branch>Creates a new branch.git branch feature/analytics
git branch -d <branch>Deletes a local branch (only if merged).git branch -d feature/old-feature
git branch -D <branch>Force-deletes a local branch (even if unmerged).git branch -D feature/risky-experiment
git push <remote> --delete <branch>Deletes a remote branch.git push origin --delete feature/old-feature

Switching Branches

CommandDescriptionExample
git checkout <branch>Switches to an existing branch.git checkout develop
git checkout -b <new-branch>Creates a new branch and switches to it.git checkout -b feature/user-profile
git switch <branch>Modern alternative to git checkout for switching branches.git switch main
git switch -c <new-branch>Modern alternative to git checkout -b for creating and switching.git switch -c bugfix/typo
git checkout -Switches to the previously checked-out branch.git checkout -

Merging Branches

CommandDescriptionExample
git merge <branch>Merges the specified branch into the current branch.git merge feature/user-profile
git merge --abortAborts a merge in case of conflicts.git merge --abort
git mergetoolLaunches a graphical merge tool to resolve conflicts.git mergetool

Resolving Merge Conflicts

When Git cannot automatically merge changes, you’ll encounter a conflict.

Use Case: Merging feature/A into main, both branches modified the same line in file.txt.

  1. Initiate Merge:

    git checkout main
    git pull origin main # Ensure main is up-to-date
    git merge feature/A
    

    Git will report conflicts, e.g., CONFLICT (content): Merge conflict in file.txt.

  2. Identify Conflicts: Open the conflicted file (file.txt). You’ll see conflict markers:

    <<<<<<< HEAD
    This is the line from main.
    =======
    This is the line from feature/A.
    >>>>>>> feature/A
    
    • <<<<<<< HEAD: Changes from the current branch (main).
    • =======: Separator.
    • >>>>>>> feature/A: Changes from the branch being merged (feature/A).
  3. Resolve Conflicts: Edit the file to the desired state, removing all conflict markers.

    This is the resolved line, combining both changes.
    
  4. Stage Resolved Files:

    git add file.txt
    

    Repeat for all conflicted files.

  5. Commit Merge:

    git commit -m "Merge feature/A into main, resolved conflicts"
    

    Git pre-populates a merge commit message; you can modify it or save as is.


Advanced Operations

Stashing Changes

Temporarily saves changes that are not ready to be committed.

CommandDescriptionExample
git stashStashes current changes (staged and unstaged).git stash
git stash save "message"Stashes with a descriptive message.git stash save "WIP: login form"
git stash listLists all stashed changes.git stash list
git stash popApplies the most recent stash and removes it from the stash list.git stash pop
git stash applyApplies the most recent stash but keeps it in the stash list.git stash apply
git stash apply stash@{n}Applies a specific stash from the list.git stash apply stash@{1}
git stash dropRemoves the most recent stash.git stash drop
git stash clearRemoves all stashed entries.git stash clear

Rebasing

Rewrites commit history by moving or combining commits. Use with caution, especially on shared branches.

Concept: git rebase

# Syntax
git rebase [options] [base]

Explanation: Reapplies commits from your current branch onto another base branch. It creates a linear history by moving your branch’s commits to the tip of the base branch. Use Case:

  • To keep your feature branch up-to-date with main before merging, creating a clean, linear history.
  • To squash multiple small commits into a single, meaningful commit.

Example: Rebase feature/X onto main

git checkout feature/X
git rebase main

If conflicts occur during rebase:

  1. Resolve conflicts in the file(s).
  2. git add <resolved-file>
  3. git rebase --continue To abort a rebase:
git rebase --abort

Interactive Rebase

Concept: git rebase -i (interactive)

# Syntax
git rebase -i [commit-hash or HEAD~N]

Explanation: Allows you to modify individual commits in a series. Git opens an editor with a list of commits and actions (pick, reword, edit, squash, fixup, drop). Use Case:

  • Cleaning up messy commit history before pushing or merging.
  • Squashing multiple small commits into one.
  • Rewording commit messages.
  • Reordering commits.
  • Deleting commits.

Example: Interactive rebase on the last 3 commits

git rebase -i HEAD~3

This will open an editor with something like:

pick 76f8e9c Add user model
pick a1b2c3d Fix typo in user controller
pick d4e5f6g Implement user authentication

# Rebase 5a6b7c8..d4e5f6g onto 5a6b7c8 (3 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified). Use -c <commit> to re-use the given commit's
# .       message but edit it.
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#

Change pick to squash or fixup to combine commits, reword to change messages, or drop to remove. Save and exit the editor.


Undoing Changes & Recovery

Unstaging Files

CommandDescriptionExample
git restore --staged <file>Unstages a file, moving it from the staging area back to the working directory.git restore --staged index.html

Discarding Local Changes

CommandDescriptionExample
git restore <file>Discards unstaged changes in a specific file.git restore src/App.js
git restore .Discards all unstaged changes in the current directory.git restore .
git clean -fdRemoves untracked files and directories from the working tree. Use with caution!git clean -fd

Amending Commits

CommandDescriptionExample
git commit --amendRewrites the last commit. Useful for fixing commit messages or adding forgotten files.git commit --amend -m "Corrected commit message"
git commit --amend --no-editAmends the last commit without changing its message.git commit --amend --no-edit

Reverting Commits

Concept: git revert

# Syntax
git revert <commit-hash>

Explanation: Creates a new commit that undoes the changes introduced by a specified commit. It’s a safe way to undo changes on shared history because it doesn’t rewrite history. Use Case: Undoing a bad commit that has already been pushed to a shared remote repository.

Example: Revert a specific commit

git revert a1b2c3d # Reverts commit a1b2c3d, creating a new commit

Resetting Commits

Concept: git reset

# Syntax
git reset [--soft | --mixed | --hard] <commit-hash or HEAD~N>

Explanation: Moves the current branch’s HEAD to a specified commit. This rewrites history and should be used with extreme caution on shared branches. Use Case: Undoing local commits that haven’t been pushed yet, or cleaning up local history.

ModeDescriptionExample
git reset --soft <commit>Moves HEAD to <commit>, but keeps changes staged.git reset --soft HEAD~1
git reset --mixed <commit>Moves HEAD to <commit>, unstages changes (default).git reset --mixed HEAD~2
git reset --hard <commit>Moves HEAD to <commit>, discards all changes (staged and unstaged). DANGER! Data loss possible.git reset --hard HEAD~3
git reset --hard ORIG_HEADUndoes the last git merge or git pull.git reset --hard ORIG_HEAD

Using Reflog for Recovery

Concept: git reflog

# Syntax
git reflog [show]

Explanation: Records every change to HEAD (e.g., commits, merges, rebases, resets). It’s a powerful safety net for recovering lost commits or states. Use Case: Recovering from an accidental git reset --hard or a failed rebase.

Example:

  1. View reflog:
    git reflog
    
    Output might look like:
    a1b2c3d HEAD@{0}: commit: Add feature X
    e4f5g6h HEAD@{1}: rebase (finish): returning to refs/heads/main
    ...
    
  2. Identify the desired state (e.g., e4f5g6h).
  3. Reset to that state:
    git reset --hard e4f5g6h
    
    This will restore your repository to the state it was at that point in the reflog.

Tagging

CommandDescriptionExample
git tagLists all tags.git tag
git tag -a <tag-name> -m "message"Creates an annotated (signed, with message) tag.git tag -a v1.0.0 -m "Release version 1.0.0"
git tag <tag-name>Creates a lightweight (unsigned) tag.git tag v1.0.0-beta
git push <remote> <tag-name>Pushes a specific tag to the remote.git push origin v1.0.0
git push <remote> --tagsPushes all local tags to the remote.git push origin --tags
git tag -d <tag-name>Deletes a local tag.git tag -d v1.0.0-beta
git push <remote> --delete <tag-name>Deletes a remote tag.git push origin --delete v1.0.0-beta

Common Patterns & Workflows

Feature Branch Workflow

  1. Update main (or develop):
    git checkout main
    git pull origin main
    
  2. Create a new feature branch:
    git checkout -b feature/my-new-feature
    
  3. Develop and commit:
    # Make changes
    git add .
    git commit -m "feat: implement X"
    
  4. Keep branch updated (optional but recommended):
    git checkout main
    git pull origin main
    git checkout feature/my-new-feature
    git rebase main # Or git merge main, if preferred for history
    
  5. Push to remote:
    git push -u origin feature/my-new-feature
    
  6. Create a Pull Request (PR): On GitHub/GitLab/Bitbucket.
  7. Merge: After review, merge feature/my-new-feature into main.

Squashing Commits Before Merge/Push

To maintain a clean history, squash multiple small commits into one meaningful commit before merging or pushing.

git checkout feature/my-feature
git rebase -i HEAD~N # N is the number of commits to squash
# In the editor, change 'pick' to 'squash' or 'fixup' for subsequent commits
# Save and exit. Git will prompt for a new commit message.
git push origin feature/my-feature --force # Use --force only if already pushed and you know what you're doing

Warning: Force-pushing rewrites history. Only do this on branches that you are the sole developer on, or after coordinating with your team.

Keeping Local Branch Updated

To ensure your local branch has the latest changes from the remote:

git checkout main # Or your base branch, e.g., develop
git pull origin main

Then, if on a feature branch:

git checkout feature/my-feature
git rebase main # Applies your changes on top of the latest main
# OR
git merge main # Creates a merge commit

Tips & Tricks

Git Aliases

Shorten frequently used commands.

git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.lg "log --graph --oneline --decorate --all"

Now you can use git co, git br, git ci, git st, git lg.

.gitignore

Specify intentionally untracked files that Git should ignore.

# Example .gitignore content
# Logs
*.log
npm-debug.log*

# Dependencies
node_modules/
.venv/

# IDE files
.idea/
.vscode/

# Build artifacts
build/
dist/

Commit Message Best Practices

  • Subject Line: Concise summary (50-72 chars), imperative mood, no period.
    • feat: Add user authentication module
    • fix: Resolve login button responsiveness
  • Body (optional): More detailed explanation, why the change, what problem it solves.
  • Conventional Commits: Use prefixes like feat:, fix:, chore:, docs:, style:, refactor:, test:, perf:, ci:.

Interactive Staging

Stage only parts of a file.

git add -p <file>

Git will present hunks (sections of changes) and ask whether to stage them (y/n/a/d/g/e/?).

Viewing Diffs

CommandDescriptionExample
git diff <commit1> <commit2>Shows diff between two commits.git diff HEAD~1 HEAD
git diff <branch1>..<branch2>Shows diff between the tips of two branches.git diff main..feature/X
git diff --name-only <commit>Shows only the names of files changed in a commit.git diff --name-only HEAD~1

Common Errors & Fixes

ErrorDescriptionFix
detached HEADYou are on a specific commit, not a branch. Committing here creates commits not associated with any branch.git switch -c <new-branch-name> (to create a branch from current HEAD) or git switch <existing-branch> (to go back to a branch).
merge conflictGit can’t automatically reconcile changes between branches.Manually edit files, git add <file>, git commit. Use git mergetool for visual aid.
fatal: refusing to merge unrelated historiesOccurs when trying to merge two repositories that started independently.git pull origin main --allow-unrelated-histories (use with caution, typically for initial merges).
fatal: repository not foundIncorrect remote URL or insufficient permissions.Check URL (git remote -v), verify permissions, or ensure SSH keys are set up correctly.
Updates were rejected because the tip of your current branch is behind its remote counterpart.Remote branch has new commits you don’t have locally.git pull (to fetch and merge) or git fetch then git rebase (to rebase your changes on top).
error: failed to push some refs to...Similar to above, usually due to remote having new commits.git pull --rebase (if you want to rebase your local commits on top of remote) or git pull then git push.
Accidental commit to mainCommitted directly to main instead of a feature branch.If not pushed: git reset HEAD~1 then git checkout -b new-feature and git commit. If pushed: git revert <commit-hash> (safer for shared history) or git reset --hard HEAD~1 then git push --force (DANGER, only if coordinated).
Large files (fatal: large files detected)Trying to add very large files directly to Git.Use Git LFS (Large File Storage): git lfs install, git lfs track "*.zip", git add .gitattributes, git commit.

Collaboration Workflows & Best Practices

  1. Feature Branching: Always work on dedicated branches for new features, bug fixes, or experiments. Never commit directly to main (or develop).
  2. Pull Requests (PRs)/Merge Requests (MRs): Use PRs/MRs for code review and discussion before merging changes into main integration branches.
  3. Small, Atomic Commits: Each commit should represent a single logical change. This makes history easier to understand and revert if needed.
  4. Descriptive Commit Messages: Follow conventional commit guidelines (feat:, fix:, etc.) and provide clear, concise messages.
  5. Rebase vs. Merge:
    • Merge: Preserves history, including merge commits. Good for public, shared branches (e.g., merging feature into main).
    • Rebase: Creates a linear history by rewriting commits. Good for cleaning up personal feature branches before merging into a shared branch. Never rebase a public/shared branch.
  6. Keep Branches Up-to-Date: Regularly pull from the main integration branch (main/develop) into your feature branch (using git pull --rebase or git fetch then git rebase) to minimize merge conflicts.
  7. Use .gitignore: Prevent unnecessary files (e.g., node_modules, .env, build artifacts) from being tracked.
  8. Review Code: Actively participate in code reviews, providing constructive feedback and learning from others.
  9. Don’t Force Push Shared Branches: Force pushing (git push --force) rewrites history and can cause significant problems for collaborators. Only force push if you are absolutely sure of the implications and have coordinated with your team.

Version Information

This cheatsheet is based on Git features and best practices relevant for Git version 2.45.0 (or similar stable release) as of 2025-12-23. Git maintains strong backward compatibility, so most commands will work across various versions. However, newer commands like git switch and git restore might not be available in very old Git clients.


References

  1. Official Git Documentation
  2. Git SCM Cheat Sheet
  3. Usama.codes - Git Commands Cheat Sheet 2025
  4. Codecademy - How to Use Git Rebase
  5. Mergify - Essential Git Workflow Best Practices

Transparency Note

This cheatsheet was generated by an AI expert based on the provided query and search context, aiming for accuracy and relevance as of December 2025. While every effort has been made to ensure correctness, always refer to the official Git documentation for the most authoritative and up-to-date information.