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:
- Tracks changes: See exactly what changed, when, and by whom
- Enables collaboration: Multiple developers can work on the same project simultaneously
- Provides history: Go back to any previous version of your code
- Manages branches: Work on features independently without affecting the main codebase
- Facilitates code review: Review changes before merging them into the main branch
- Improves accountability: Track who made which changes and why
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.
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
Sets your name for all commits globally on your system.
git config --global user.name "John Developer"
Sets your email address for all commits globally. Use your GitHub email if you're using GitHub.
git config --global user.email "john@example.com"
Sets your default text editor for commit messages. Options: vim, nano, code, gedit, etc.
git config --global core.editor "code"
Viewing Configuration
Displays all Git configuration settings.
Displays all global Git configuration settings.
Displays your configured username.
Project-Specific Configuration
Sets the user name for only the current repository (without --global flag). Useful for work projects with different identities.
3. Creating & Cloning Repositories
Start your version control journey by either initializing a new repository or cloning an existing one.
Initialize a New Repository
Initializes a new Git repository in the current directory. Creates a .git folder that stores all version control information.
mkdir my-project && cd my-project && git init
Creates a new directory and initializes a Git repository inside it.
git init my-awesome-app
Clone a Repository
Creates a local copy of a remote repository. Downloads all files, branches, and history.
git clone https://github.com/user/repo.git
Clones the repository into a directory with a custom name.
git clone https://github.com/user/repo.git my-local-copy
Clones only a specific branch from the repository.
git clone --branch develop https://github.com/user/repo.git
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
Shows the current status of your repository. Displays modified, staged, and untracked files.
Displays a compact status view with abbreviated output.
Staging Changes
Stages a specific file for the next commit.
git add src/main.js
Stages all changes in the current directory and subdirectories.
Stages all changes in the entire repository, including deletions.
Interactive staging. Allows you to review and stage changes hunk-by-hunk. Excellent for splitting large changes into smaller commits.
$ git add -p
Stage this hunk? [y,n,q,a,d,e,?] y
Unstaging Changes
Unstages a specific file without modifying the file itself.
Unstages all staged changes.
Viewing Staged vs Unstaged
Shows unstaged changes between your working directory and the last commit.
Shows staged changes that will be included in the next commit.
Creating Commits
Commits staged changes with a message. Keep messages clear and descriptive.
git commit -m "Fix login button alignment on mobile"
Automatically stages all tracked files and commits them. Skips untracked files.
Modifies the last commit. Add new changes, update the message, or both. Don't use on pushed commits!
git add forgotten-file.js && git commit --amend --no-edit
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
Lists all local branches. The current branch is marked with an asterisk (*).
Lists both local and remote branches.
Lists branches with the latest commit on each.
Creating Branches
Creates a new branch from the current branch. Doesn't switch to it automatically.
git branch feature/user-authentication
Creates and switches to a new branch in one command.
git checkout -b feature/payment-integration
Modern alternative to checkout. Creates and switches to a new branch.
git switch -c fix/login-bug
Switching Branches
Switches to an existing branch. Your working directory updates to reflect the branch's state.
Modern alternative to checkout for switching branches.
Deleting Branches
Deletes a branch. Only works if the branch is fully merged. Safe option.
Force deletes a branch without checking if it's merged. Use carefully!
Merging Branches
Merges the specified branch into the current branch. Creates a merge commit.
git checkout main && git merge feature/authentication
Merges with an explicit merge commit, even if a fast-forward is possible. Keeps branch history visible.
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:
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
Lists all remote repository names. Usually starts with "origin" (the default remote).
Shows remote names and their URLs for fetching and pushing.
Displays detailed information about a remote repository.
Adding Remotes
Adds a new remote repository.
git remote add origin https://github.com/user/repo.git
Fetching Changes
Downloads changes from the remote repository but doesn't merge them. Safe way to check for updates.
Fetches from a specific remote.
Fetches a specific branch from a remote.
Pulling Changes
Fetches and merges changes from the remote branch into your current branch. Equivalent to git fetch + git merge.
Fetches and rebases your changes on top of the remote changes. Creates a cleaner history without merge commits.
Pulls from a specific remote and branch.
Pushing Changes
Pushes your local commits to the remote repository (usually origin master or main).
Pushes to a specific remote and branch.
git push origin feature/new-dashboard
Pushes and sets the upstream branch. After this, you can just use "git push" without specifying the remote and branch.
Pushes all branches to the remote repository.
Deletes a branch on the remote repository.
Updating Remote References
Renames a remote repository reference.
Removes a remote repository reference.
Changes the URL of an existing remote.
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
Saves all staged and unstaged changes to a stash and reverts the working directory to clean.
git stash
Saved working directory and index state WIP on main: abc1234
Stashes changes with a descriptive message for easier identification later.
Stashes including untracked files.
Viewing Stashes
Lists all stashes. Format: stash@{0}, stash@{1}, etc.
Shows the latest stash changes.
Shows specific stash changes.
git stash show stash@{2}
Applying Stashes
Applies the latest stash without removing it from the stash list.
Applies the latest stash and removes it from the stash list.
Applies a specific stash.
Managing Stashes
Deletes the latest stash.
Deletes a specific stash.
Deletes all stashes. Use carefully!
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
Shows the commit history for the current branch. Press 'q' to exit.
Shows a compact log with one commit per line. Great for quick overview.
Shows the last 10 commits in compact format.
Detailed Logging
Shows commits with their full changes (diffs).
Shows commits with file statistics (files changed, additions, deletions).
Shows a visual graph of branches and merges. Excellent for understanding project structure.
Filtering Logs
Shows commits by a specific author.
Shows commits from the last 2 weeks.
Shows commits up to a specific date.
Shows commits with messages matching the grep pattern (case-sensitive).
Shows commits that modified a specific file.
git log -- src/components/Button.js
Detailed Commit Information
Shows detailed information about a specific commit including changes.
Shows only the most recent commit.
Shows which commit and author last modified each line of a file. Useful for tracking down when bugs were introduced.
Useful Log Formatting
Custom format showing abbreviated SHA, author, date, and subject.
%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)
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
Discards changes to a file in the working directory. Cannot be undone!
git checkout -- src/app.js
Modern alternative to checkout for discarding changes.
Undoing Staged Changes
Unstages a file but keeps changes in working directory.
Same as above - unstages without affecting the working directory.
Undoing Commits (Local Only)
Undoes the last commit but keeps changes staged. Useful for fixing commit message or adding more changes.
Undoes the last commit and unstages changes (default behavior).
Completely removes the last commit and all its changes. Cannot be undone!
Undoing Commits (Preserving History)
Creates a new commit that undoes the changes from a specific commit. Preserves history and is safe for pushed commits.
git revert abc1234
# This creates a new commit with reverse changes
Creates a new commit that undoes the last commit.
Reverts without automatically committing. Allows you to modify the revert before committing.
Going Back to a Previous State
Resets to a previous commit, keeping changes in working directory.
Resets to a previous commit, discarding all changes.
Need to review and compare changes?
Use our Diff Viewer to visually compare file versions and understand exactly what changed.
Open Diff Viewer10. 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.
Rebases current branch onto another branch.
git checkout feature/new-ui && git rebase main
Starts an interactive rebase for the last 3 commits. Allows reordering, squashing, and editing commits.
Continues rebasing after resolving conflicts.
Cancels the rebase and returns to the original state.
Cherry-Picking
Cherry-pick applies a specific commit from one branch to another.
Applies a specific commit to the current branch.
git cherry-pick abc1234
Cherry-picks multiple commits.
Cherry-picks a range of commits (exclusive of start commit).
Continues cherry-picking after resolving conflicts.
Binary Search for Bugs β Bisect
Git bisect uses binary search to find the commit that introduced a bug.
Starts a bisect session.
Marks the current commit as bad (contains the bug).
Marks a specific commit as good (bug-free).
Ends the bisect session and returns to the original branch.
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
Finds commits where a specific term was added or removed from the code.
Searches for a pattern in the working directory.
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
Creates the alias 'st' for 'status'.
git st # instead of git status
Creates the alias 'co' for 'checkout'.
Creates the alias 'br' for 'branch'.
Creates the alias 'ci' for 'commit'.
Creating Complex Aliases
Creates a meaningful alias for unstaging files.
Shows the last commit.
Shows a visual representation of the repository history.
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
Lists all global aliases (may show nothing if no aliases are configured).
Lists all aliases in global configuration.
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
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
__pycache__/
*.py[cod]
*.egg-info/
venv/
.venv/
node_modules/
npm-debug.log
yarn-error.log
.npm
dist/
build/
.env
.env.local
.DS_Store
.vscode/
.idea/
*.swp
*.swo
*~
Checking Ignored Files
Shows if a file is ignored and which rule matches it.
Shows verbose output with the specific .gitignore line that ignores the file.
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 .gitignore13. 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
- Use imperative mood: "Add feature" instead of "Added feature" or "Adds feature"
- Don't end with a period: "Fix login bug" not "Fix login bug."
- Limit the subject to 50 characters: Forces conciseness
- Separate subject from body with a blank line: Makes logs readable
- Wrap body at 72 characters: For readable terminal display
- Explain WHAT and WHY, not HOW: The code shows how; explain the reason for change
Conventional Commits Format
Many projects use conventional commits for structured messages:
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
fixed stuff
updated code
bug fix
work in progress
asdf
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 Message14. 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
- Practice daily: The more you use Git, the more natural these commands become
- Create aliases: Set up the aliases from Section 11 to speed up your workflow
- Focus on branching: Master git branch and git merge for feature development
- Write good messages: Invest time in clear commit messages - future you will appreciate it
- Learn from mistakes: Git allows you to undo almost anything, so experiment fearlessly
Resources & Tools
We've built companion tools to enhance your Git workflow:
Key Takeaways
- 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.