Git Cheat Sheet

Essential Commands Every Developer Needs (2025)
Complete reference guide with examples and best practices

1. Introduction β€” Why Every Developer Needs Git

Git is the most widely-used version control system in the world. Whether you're working on personal projects, collaborating with a small team, or contributing to open-source software with thousands of developers, Git is the foundation of modern software development.

Version control is essential because it:

This comprehensive Git cheat sheet covers everything from basic commands to advanced techniques. Whether you're a beginner just starting with Git or an experienced developer looking for a quick reference, you'll find the commands and workflows you need here.

πŸ’‘ Pro Tip: Bookmark this page for quick reference. Git commands may seem overwhelming at first, but with practice, they become second nature.

2. Setup & Config Commands

Before you start using Git, you need to configure your identity. These configuration commands set up your user information for all commits.

Initial Configuration

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

Sets your name for all commits globally on your system.

Example: git config --global user.name "John Developer"
git config --global user.email "your.email@example.com"

Sets your email address for all commits globally. Use your GitHub email if you're using GitHub.

Example: git config --global user.email "john@example.com"
git config --global core.editor "vim"

Sets your default text editor for commit messages. Options: vim, nano, code, gedit, etc.

Example: git config --global core.editor "code"

Viewing Configuration

git config --list

Displays all Git configuration settings.

git config --global --list

Displays all global Git configuration settings.

git config user.name

Displays your configured username.

Project-Specific Configuration

git config user.name "Different Name"

Sets the user name for only the current repository (without --global flag). Useful for work projects with different identities.

βš™οΈ Note: Global configuration is stored in ~/.gitconfig, while project-specific config is in .git/config within your repository.

3. Creating & Cloning Repositories

Start your version control journey by either initializing a new repository or cloning an existing one.

Initialize a New Repository

git init

Initializes a new Git repository in the current directory. Creates a .git folder that stores all version control information.

Example: mkdir my-project && cd my-project && git init
git init [project-name]

Creates a new directory and initializes a Git repository inside it.

Example: git init my-awesome-app

Clone a Repository

git clone [url]

Creates a local copy of a remote repository. Downloads all files, branches, and history.

Example: git clone https://github.com/user/repo.git
git clone [url] [directory-name]

Clones the repository into a directory with a custom name.

Example: git clone https://github.com/user/repo.git my-local-copy
git clone --branch [branch-name] [url]

Clones only a specific branch from the repository.

Example: git clone --branch develop https://github.com/user/repo.git
πŸ’‘ SSH vs HTTPS: If you've set up SSH keys, use SSH URLs (git@github.com:user/repo.git) for faster, authentication-free clones.

4. Staging & Committing with Interactive Examples

Staging allows you to choose which changes to include in your next commit. This workflow ensures clean, logical commits with related changes.

Checking Status

git status

Shows the current status of your repository. Displays modified, staged, and untracked files.

git status --short

Displays a compact status view with abbreviated output.

Staging Changes

git add [file-name]

Stages a specific file for the next commit.

Example: git add src/main.js
git add .

Stages all changes in the current directory and subdirectories.

git add -A

Stages all changes in the entire repository, including deletions.

git add -p

Interactive staging. Allows you to review and stage changes hunk-by-hunk. Excellent for splitting large changes into smaller commits.

Example: $ git add -p Stage this hunk? [y,n,q,a,d,e,?] y

Unstaging Changes

git reset [file-name]

Unstages a specific file without modifying the file itself.

git reset

Unstages all staged changes.

Viewing Staged vs Unstaged

git diff

Shows unstaged changes between your working directory and the last commit.

git diff --staged

Shows staged changes that will be included in the next commit.

Creating Commits

git commit -m "Your commit message"

Commits staged changes with a message. Keep messages clear and descriptive.

Example: git commit -m "Fix login button alignment on mobile"
git commit -am "Your commit message"

Automatically stages all tracked files and commits them. Skips untracked files.

git commit --amend

Modifies the last commit. Add new changes, update the message, or both. Don't use on pushed commits!

Example: git add forgotten-file.js && git commit --amend --no-edit
Typical Staging Workflow: Working Directory (modified files) ↓ git add Staging Area (indexed, ready to commit) ↓ git commit Repository (.git, permanent history)
βœ“ Best Practice: Write meaningful commit messages in the present tense. Example: "Add user authentication" instead of "Added user authentication".

5. Branching & Merging β€” Visual Explanation

Branches allow parallel development. Create a branch for each feature, bug fix, or experiment, then merge when ready.

Viewing Branches

git branch

Lists all local branches. The current branch is marked with an asterisk (*).

git branch -a

Lists both local and remote branches.

git branch -v

Lists branches with the latest commit on each.

Creating Branches

git branch [branch-name]

Creates a new branch from the current branch. Doesn't switch to it automatically.

Example: git branch feature/user-authentication
git checkout -b [branch-name]

Creates and switches to a new branch in one command.

Example: git checkout -b feature/payment-integration
git switch -c [branch-name]

Modern alternative to checkout. Creates and switches to a new branch.

Example: git switch -c fix/login-bug

Switching Branches

git checkout [branch-name]

Switches to an existing branch. Your working directory updates to reflect the branch's state.

git switch [branch-name]

Modern alternative to checkout for switching branches.

Deleting Branches

git branch -d [branch-name]

Deletes a branch. Only works if the branch is fully merged. Safe option.

git branch -D [branch-name]

Force deletes a branch without checking if it's merged. Use carefully!

Merging Branches

git merge [branch-name]

Merges the specified branch into the current branch. Creates a merge commit.

Example: git checkout main && git merge feature/authentication
git merge --no-ff [branch-name]

Merges with an explicit merge commit, even if a fast-forward is possible. Keeps branch history visible.

git merge --squash [branch-name]

Merges all commits from the branch into a single commit. Cleans up history before merging.

Handling Merge Conflicts

When Git can't automatically merge files, you'll get a merge conflict. Edit the conflicted files, resolve the conflicts, then:

git add [resolved-file] git commit -m "Resolve merge conflict"
Branching Visual: main ●─────●──────●────● \ / feature ●─●─●─●───● \ / ─ ─ ─ ─ ─ (merge point)
πŸ“‹ Naming Convention: Use prefixes for branches like feature/, bugfix/, hotfix/, docs/. Example: feature/dark-mode, bugfix/search-crash, docs/api-guide.

6. Remote Repositories β€” Push, Pull, Fetch

Remote repositories (like GitHub, GitLab, Bitbucket) enable collaboration. These commands manage the connection between your local and remote repositories.

Viewing Remotes

git remote

Lists all remote repository names. Usually starts with "origin" (the default remote).

git remote -v

Shows remote names and their URLs for fetching and pushing.

git remote show [remote-name]

Displays detailed information about a remote repository.

Adding Remotes

git remote add [remote-name] [url]

Adds a new remote repository.

Example: git remote add origin https://github.com/user/repo.git

Fetching Changes

git fetch

Downloads changes from the remote repository but doesn't merge them. Safe way to check for updates.

git fetch [remote-name]

Fetches from a specific remote.

git fetch [remote-name] [branch-name]

Fetches a specific branch from a remote.

Pulling Changes

git pull

Fetches and merges changes from the remote branch into your current branch. Equivalent to git fetch + git merge.

git pull --rebase

Fetches and rebases your changes on top of the remote changes. Creates a cleaner history without merge commits.

git pull [remote-name] [branch-name]

Pulls from a specific remote and branch.

Pushing Changes

git push

Pushes your local commits to the remote repository (usually origin master or main).

git push [remote-name] [branch-name]

Pushes to a specific remote and branch.

Example: git push origin feature/new-dashboard
git push -u [remote-name] [branch-name]

Pushes and sets the upstream branch. After this, you can just use "git push" without specifying the remote and branch.

git push [remote-name] --all

Pushes all branches to the remote repository.

git push [remote-name] --delete [branch-name]

Deletes a branch on the remote repository.

Updating Remote References

git remote rename [old-name] [new-name]

Renames a remote repository reference.

git remote remove [remote-name]

Removes a remote repository reference.

git remote set-url [remote-name] [new-url]

Changes the URL of an existing remote.

πŸ”„ Fetch vs Pull: Fetch is safer for checking changes without merging. Pull is more convenient for quickly getting updates. Use fetch when reviewing changes first.

7. Stashing β€” Save Work Without Committing

Stashing temporarily saves your changes without committing them. Useful when you need to switch branches or pull updates without committing incomplete work.

Creating Stashes

git stash

Saves all staged and unstaged changes to a stash and reverts the working directory to clean.

Example: git stash Saved working directory and index state WIP on main: abc1234
git stash save "descriptive message"

Stashes changes with a descriptive message for easier identification later.

git stash -u

Stashes including untracked files.

Viewing Stashes

git stash list

Lists all stashes. Format: stash@{0}, stash@{1}, etc.

git stash show

Shows the latest stash changes.

git stash show [stash-id]

Shows specific stash changes.

Example: git stash show stash@{2}

Applying Stashes

git stash apply

Applies the latest stash without removing it from the stash list.

git stash pop

Applies the latest stash and removes it from the stash list.

git stash apply [stash-id]

Applies a specific stash.

Managing Stashes

git stash drop

Deletes the latest stash.

git stash drop [stash-id]

Deletes a specific stash.

git stash clear

Deletes all stashes. Use carefully!

πŸ’Ύ Stash Use Cases: Use stashing when you need to switch branches quickly, pull urgent updates, or save experimental changes without committing.

8. Log & History β€” Understanding Your Repository's Past

Git's log commands help you understand the history of your project, find when bugs were introduced, and understand why changes were made.

Basic Logging

git log

Shows the commit history for the current branch. Press 'q' to exit.

git log --oneline

Shows a compact log with one commit per line. Great for quick overview.

git log --oneline -10

Shows the last 10 commits in compact format.

Detailed Logging

git log -p

Shows commits with their full changes (diffs).

git log --stat

Shows commits with file statistics (files changed, additions, deletions).

git log --graph --oneline --all

Shows a visual graph of branches and merges. Excellent for understanding project structure.

Filtering Logs

git log --author="John"

Shows commits by a specific author.

git log --since="2 weeks ago"

Shows commits from the last 2 weeks.

git log --until="2023-12-31"

Shows commits up to a specific date.

git log --grep="bug fix"

Shows commits with messages matching the grep pattern (case-sensitive).

git log -- [file-path]

Shows commits that modified a specific file.

Example: git log -- src/components/Button.js

Detailed Commit Information

git show [commit-sha]

Shows detailed information about a specific commit including changes.

git log -1

Shows only the most recent commit.

git blame [file-path]

Shows which commit and author last modified each line of a file. Useful for tracking down when bugs were introduced.

Useful Log Formatting

git log --pretty=format:"%h - %an (%ar): %s"

Custom format showing abbreviated SHA, author, date, and subject.

Useful format codes: %h = abbreviated commit hash %H = full commit hash %an = author name %ae = author email %ar = author date (relative) %ai = author date (ISO format) %s = subject (commit message)
πŸ“Š Tip: Create an alias for your most-used log format. See the Git Aliases section below.

9. Undoing Changes β€” Reset, Revert, Checkout

Git provides multiple ways to undo changes. Choose carefully based on whether the changes are committed and whether you need to preserve history.

Undoing Unstaged Changes

git checkout -- [file-name]

Discards changes to a file in the working directory. Cannot be undone!

Example: git checkout -- src/app.js
git restore [file-name]

Modern alternative to checkout for discarding changes.

Undoing Staged Changes

git reset HEAD [file-name]

Unstages a file but keeps changes in working directory.

git reset [file-name]

Same as above - unstages without affecting the working directory.

Undoing Commits (Local Only)

git reset --soft HEAD~1

Undoes the last commit but keeps changes staged. Useful for fixing commit message or adding more changes.

git reset --mixed HEAD~1

Undoes the last commit and unstages changes (default behavior).

git reset --hard HEAD~1

Completely removes the last commit and all its changes. Cannot be undone!

Reset Modes Comparison: --soft : ● commit is undone, changes stay staged --mixed : ● commit is undone, changes stay in working dir --hard : ● commit is undone, all changes are discarded

Undoing Commits (Preserving History)

git revert [commit-sha]

Creates a new commit that undoes the changes from a specific commit. Preserves history and is safe for pushed commits.

Example: git revert abc1234 # This creates a new commit with reverse changes
git revert HEAD

Creates a new commit that undoes the last commit.

git revert -n [commit-sha]

Reverts without automatically committing. Allows you to modify the revert before committing.

Going Back to a Previous State

git reset [commit-sha]

Resets to a previous commit, keeping changes in working directory.

git reset --hard [commit-sha]

Resets to a previous commit, discarding all changes.

⚠️ Important: Never use reset or checkout on commits you've already pushed to a shared repository. Use revert instead to preserve history and avoid conflicts with collaborators.

Need to review and compare changes?

Use our Diff Viewer to visually compare file versions and understand exactly what changed.

Open Diff Viewer

10. Advanced Techniques β€” Rebase, Cherry-Pick, Bisect

These advanced commands help you maintain clean history, apply specific changes selectively, and find problematic commits.

Rebasing

Rebasing replays your commits on top of another branch. Creates a linear history instead of merge commits.

git rebase [branch-name]

Rebases current branch onto another branch.

Example: git checkout feature/new-ui && git rebase main
git rebase -i HEAD~3

Starts an interactive rebase for the last 3 commits. Allows reordering, squashing, and editing commits.

git rebase --continue

Continues rebasing after resolving conflicts.

git rebase --abort

Cancels the rebase and returns to the original state.

Cherry-Picking

Cherry-pick applies a specific commit from one branch to another.

git cherry-pick [commit-sha]

Applies a specific commit to the current branch.

Example: git cherry-pick abc1234
git cherry-pick [commit-sha1] [commit-sha2] [commit-sha3]

Cherry-picks multiple commits.

git cherry-pick [commit-sha1]..[commit-sha2]

Cherry-picks a range of commits (exclusive of start commit).

git cherry-pick --continue

Continues cherry-picking after resolving conflicts.

Binary Search for Bugs β€” Bisect

Git bisect uses binary search to find the commit that introduced a bug.

git bisect start

Starts a bisect session.

git bisect bad

Marks the current commit as bad (contains the bug).

git bisect good [commit-sha]

Marks a specific commit as good (bug-free).

git bisect reset

Ends the bisect session and returns to the original branch.

Bisect Workflow Example: git bisect start git bisect bad HEAD git bisect good v1.0 # Git checks out middle commits for testing # You test each one... git bisect good # if this commit is OK git bisect bad # if this commit has the bug # Repeat until Git identifies the culprit git bisect reset

Finding Specific Changes β€” Grep

git log -S "search-term"

Finds commits where a specific term was added or removed from the code.

git grep "pattern"

Searches for a pattern in the working directory.

⚑ Pro Tip: Rebase is powerful but rewrites history. Never rebase public/pushed commits. Only rebase local commits.

11. Git Aliases β€” Time-Saving Shortcuts

Git aliases create shortcuts for frequently-used commands. Speed up your workflow with custom command abbreviations.

Creating Basic Aliases

git config --global alias.st status

Creates the alias 'st' for 'status'.

Usage: git st # instead of git status
git config --global alias.co checkout

Creates the alias 'co' for 'checkout'.

git config --global alias.br branch

Creates the alias 'br' for 'branch'.

git config --global alias.ci commit

Creates the alias 'ci' for 'commit'.

Creating Complex Aliases

git config --global alias.unstage 'reset HEAD --'

Creates a meaningful alias for unstaging files.

git config --global alias.last 'log -1 HEAD'

Shows the last commit.

git config --global alias.visual 'log --graph --oneline --all'

Shows a visual representation of the repository history.

git config --global alias.recent 'log --oneline -10'

Shows the 10 most recent commits.

Useful Alias Collection

Alias Command Purpose
st status Quick status check
co checkout Quick branch switching
br branch Quick branch listing
ci commit Quick committing
amend commit --amend Modify last commit
undo reset --soft HEAD~ Undo last commit (keep changes)
unstage reset HEAD -- Unstage files

View Your Aliases

git config --global alias

Lists all global aliases (may show nothing if no aliases are configured).

git config --global --list | grep alias

Lists all aliases in global configuration.

πŸ’‘ Shell Aliases vs Git Aliases: You can also create shell aliases (in .bashrc or .zshrc) like alias gs="git status", but Git aliases are more portable across different systems.

12. .gitignore Patterns β€” Controlling What Gets Tracked

The .gitignore file specifies files and directories that Git should ignore. This prevents committing generated files, dependencies, and sensitive data.

Basic .gitignore Syntax

# Comment - this line is ignored *.log # Ignore all .log files *.tmp # Ignore all .tmp files node_modules/ # Ignore the node_modules directory .env # Ignore the .env file dist/ # Ignore the dist directory

Common Patterns

Pattern Matches
*.log All files ending with .log
debug.log Specific file named debug.log
/config.js File in root directory only
build/ All files in build directory
**/*.test.js All .test.js files in any directory
!important.log Exception - DO track this file
temp/* All files in temp (but not subdirs)

Language-Specific .gitignore

Python: __pycache__/ *.py[cod] *.egg-info/ venv/ .venv/
Node.js: node_modules/ npm-debug.log yarn-error.log .npm dist/ build/
General (all projects): .env .env.local .DS_Store .vscode/ .idea/ *.swp *.swo *~

Checking Ignored Files

git check-ignore [file-path]

Shows if a file is ignored and which rule matches it.

git check-ignore -v [file-path]

Shows verbose output with the specific .gitignore line that ignores the file.

git clean -fdn

Dry run - shows which untracked files would be removed. Use -fd (no -n) to actually delete.

Generate .gitignore automatically

Don't want to create .gitignore from scratch? Use our tool to generate patterns for your tech stack.

Generate .gitignore
πŸš€ Pro Tip: Create a global .gitignore file for your system-wide exclusions (.DS_Store, IDE files, etc). Configure it with: git config --global core.excludesfile ~/.gitignore_global

13. Commit Message Best Practices

Good commit messages are essential for project maintenance. Future developers (including yourself!) will thank you for clear, descriptive messages.

The Golden Rules

Conventional Commits Format

Many projects use conventional commits for structured messages:

type(scope): subject Body explaining the change in more detail. Closes #123
Example: feat(auth): add two-factor authentication Implement TOTP-based 2FA for enhanced security. Users can enable 2FA in account settings. - Add TOTP generation and verification - Update login flow to support 2FA - Add database migrations for tokens Closes #456

Commit Types

Type Purpose
feat New feature or functionality
fix Bug fix
docs Documentation changes
style Formatting, missing semicolons, etc
refactor Code reorganization without behavior change
perf Performance improvements
test Test additions or modifications
chore Build, dependencies, tools

Examples of Good vs Bad Commits

❌ Bad: fixed stuff updated code bug fix work in progress asdf
βœ“ Good: fix(button): prevent multiple submissions on quick click feat(api): add pagination to user list endpoint docs: update setup instructions for macOS refactor(auth): extract token validation to helper

Need help crafting commit messages?

Use our AI-powered tool to generate clear, well-structured commit messages automatically.

Generate Commit Message

14. Frequently Asked Questions

How do I fix a commit I already pushed? β–Ό

If you need to fix a commit you've already pushed, use git revert to create a new commit that undoes the changes. Never use git reset on pushed commits because it rewrites history and conflicts with other developers' work.

Example:

git revert abc1234 # creates a new commit

If it's a private branch only you're using, you can force push after reset: git reset --hard HEAD~1 && git push --force-with-lease

What's the difference between git pull and git fetch? β–Ό

git fetch downloads changes from the remote but doesn't merge them. Your working directory stays unchanged. Safe for reviewing changes first.

git pull does git fetch AND git merge in one command. It immediately integrates remote changes into your current branch. More convenient but less control.

Recommended workflow: Use fetch to check for changes, then merge manually after review. This gives you more control and understanding of what you're pulling.

How do I undo multiple commits? β–Ό

For local commits not yet pushed, use git reset:

git reset --soft HEAD~3 # undo 3 commits, keep changes staged git reset --hard HEAD~3 # undo 3 commits, discard changes

For pushed commits, use git revert with a range:

git revert --no-edit HEAD~2..HEAD # reverts the last 2 commits

What should I do if I accidentally deleted a file? β–Ό

Git tracks all commits, so deleted files can be recovered. First, find the commit where the file existed:

git log --full-history -- path/to/file.js

Then restore it:

git checkout abc1234^ -- path/to/file.js # abc1234^ is the commit before the deletion

Or restore to the current branch and add in a new commit:

git restore --source=HEAD~1 path/to/file.js

How do I resolve merge conflicts? β–Ό

When Git can't automatically merge, conflict markers appear in files:

<<<<<<< HEAD your changes here ======= their changes here >>>>>>> branch-name

Edit the file to keep the code you want, then remove the conflict markers. After resolving all conflicts:

git add . git commit -m "Resolve merge conflict"

Use a visual merge tool for complex conflicts: git mergetool

15. Conclusion β€” Your Git Mastery Journey

You now have a comprehensive understanding of Git commands and workflows. Git is a powerful tool, and while there's much to learn, the commands in this cheat sheet cover 95% of real-world development scenarios.

Your Next Steps

Resources & Tools

We've built companion tools to enhance your Git workflow:

Key Takeaways

Remember these core concepts:
  • Commits are permanent: Once committed, changes are safely stored in history
  • Branches are cheap: Create branches liberally for features and experiments
  • Pull before push: Always pull latest changes before pushing your work
  • Meaningful messages matter: Take 30 seconds to write a good commit message
  • Revert, don't reset (for pushed commits): Preserve history for collaboration

Git is more than just a tool for backing up codeβ€”it's a communication system for your team. Every commit tells a story of the project's evolution. Use it wisely, and your codebase will be a pleasure to work with.

Happy coding! πŸš€
Master Git, and you'll master collaborative development.

\xF0\x9F\x92\x99 Tip\xF0\x9F\x93\x9A Get Bundle \x244.99