Git is the backbone of modern software development, yet many developers only scratch the surface of its capabilities. Whether you're committing your first change or managing complex collaborative workflows, having a solid Git reference can save hours of frustration.
This comprehensive cheatsheet covers everything from basic commands to advanced operations, organized by use case so you can quickly find what you need.
Setup and Configuration
Before diving into Git commands, let's configure your environment properly.
Initial Setup
Start a new repository:
git initCreates a new Git repository in the current directory. This initializes the .git folder containing all version control metadata.
Clone an existing repository:
git clone https://github.com/username/repository.gitCreates a local copy of a remote repository, including all commit history and branches.
Clone to a specific directory:
git clone https://github.com/username/repository.git my-projectConfiguration Essentials
Set your identity globally:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"These settings appear in every commit you make. Use --global for all repositories, or --local for repository-specific settings.
View all configuration:
git config --listShows all Git settings, including user info, aliases, and editor preferences.
Set your preferred editor:
git config --global core.editor "code --wait" # VS Code
git config --global core.editor "vim" # Vim
git config --global core.editor "nano" # NanoThis editor opens when Git needs commit messages or interactive operations.
Enable colored output:
git config --global color.ui autoMakes Git output more readable with color-coded information.
Create command shortcuts (aliases):
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.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'Now you can use git co instead of git checkout, git st instead of git status, etc.
Cache credentials temporarily:
git config --global credential.helper 'cache --timeout=3600'Caches your Git credentials for 1 hour (3600 seconds), avoiding repeated password prompts.
File Operations
Basic File Management
Check repository status:
git statusShows which files are staged, unstaged, or untracked. This should be your most-used Git command.
Stage files for commit:
git add filename.txt # Stage specific file
git add folder/ # Stage entire folder
git add *.js # Stage all JS files
git add . # Stage all changesStage interactively (choose specific changes):
git add -pLets you review and stage changes chunk by chunk—perfect for committing only related changes.
Remove files:
git rm filename.txt # Delete and stage removal
git rm --cached filename.txt # Unstage but keep in working directory
git rm -r folder/ # Recursively remove directoryRename or move files:
git mv old-name.txt new-name.txt
git mv file.txt folder/file.txtGit tracks the rename intelligently instead of treating it as delete + add.
Commit staged changes:
git commit -m "Add user authentication feature"
git commit -m "Fix bug in login flow" -m "Detailed explanation here"The first -m is the subject line, additional -m flags add body paragraphs.
Amend the last commit:
git commit --amend -m "Updated commit message"
git commit --amend --no-edit # Keep existing messageUseful for fixing typos or adding forgotten files to the last commit.
Viewing Changes
See unstaged changes:
git diffShows what you've changed but haven't staged yet.
See staged changes:
git diff --cached
git diff --stagedShows what will be included in the next commit.
Compare specific commits:
git diff abc123..def456 # Compare two commits
git diff HEAD~2..HEAD # Compare 2 commits ago to now
git diff main..feature-branch # Compare branchesSee change statistics:
git diff --statShows files changed and line counts without full diff output.
Ignore file changes temporarily:
git update-index --assume-unchanged config.local.jsTells Git to treat a tracked file as unchanged. Useful for local configuration files.
Resume tracking changes:
git update-index --no-assume-unchanged config.local.jsBranching and Merging
Branches are Git's killer feature, enabling parallel development without conflicts.
Basic Branch Operations
List all branches:
git branch # Local branches
git branch -r # Remote branches
git branch -a # All branches (local + remote)Create a new branch:
git branch feature-loginCreates the branch but doesn't switch to it.
Switch to a branch:
git checkout feature-login
git switch feature-login # Modern alternativeCreate and switch in one command:
git checkout -b feature-login
git switch -c feature-login # Modern alternativeRename a branch:
git branch -m old-name new-name # Rename any branch
git branch -m new-name # Rename current branchDelete a branch:
git branch -d feature-login # Safe delete (prevents data loss)
git branch -D feature-login # Force deleteAdvanced Branch Management
View branches with details:
git branch -vvShows last commit on each branch plus tracking information.
Create tracking branch:
git checkout -b local-branch origin/remote-branch
git branch --track local-branch origin/remote-branchSets up a local branch to track changes from a remote branch.
Set existing branch to track remote:
git branch -u origin/main
git branch --set-upstream-to=origin/mainMerging Branches
Merge a branch into current branch:
git merge feature-loginCombines the specified branch's changes into your current branch.
Merge with commit message:
git merge feature-login -m "Merge login feature"Abort a merge if conflicts arise:
git merge --abortCancels the merge and returns to the pre-merge state.
Fast-forward merge only:
git merge --ff-only feature-loginOnly merges if it can be done via fast-forward, preventing merge commits.
Rebasing
Rebase current branch onto another:
git rebase mainReplays your commits on top of the main branch, creating a linear history.
Interactive rebase (edit history):
git rebase -i HEAD~3 # Edit last 3 commits
git rebase -i abc123 # Rebase back to commit abc123Opens an editor where you can:
- Reorder commits
- Squash multiple commits into one
- Edit commit messages
- Delete commits
Continue after resolving conflicts:
git rebase --continueAbort a rebase:
git rebase --abortSkip a commit during rebase:
git rebase --skipRemote Repositories
Working with remote repositories is essential for collaboration.
Managing Remotes
List remote repositories:
git remote # Show names
git remote -v # Show names and URLsAdd a new remote:
git remote add origin https://github.com/username/repo.git
git remote add upstream https://github.com/original/repo.gitRemove a remote:
git remote rm originRename a remote:
git remote rename old-name new-nameShow remote details:
git remote show originDisplays fetch/push URLs, tracked branches, and local branch configurations.
Fetching and Pulling
Download remote changes (don't merge):
git fetch origin # Fetch from origin
git fetch --all # Fetch from all remotes
git fetch -p # Prune deleted remote branchesDownload and merge remote changes:
git pull origin main
git pull # Pull from tracked branch
git pull --rebase # Rebase instead of mergeFetch and prune obsolete remote branches:
git fetch -pRemoves local references to remote branches that no longer exist.
Pushing Changes
Push to remote branch:
git push origin main
git push origin feature-loginPush and set tracking relationship:
git push -u origin feature-loginAfter this, you can use git push without specifying remote/branch.
Force push (dangerous!):
git push --force origin main
git push --force-with-lease origin main # Safer alternative--force-with-lease prevents overwriting work if the remote has changes you don't have locally.
Push all branches:
git push --all originPush tags:
git push --tags # Push all tags
git push origin v1.0.0 # Push specific tagDelete remote branch:
git push origin --delete feature-login
git push origin :feature-login # Shorthand syntaxCommit History
Understanding your project's history is crucial for debugging and collaboration.
Viewing Commit History
Show commit history:
git logDisplays full commit history with SHA, author, date, and message.
Condensed one-line format:
git log --onelineShows abbreviated commit hash and message only.
Visualize branch structure:
git log --graph --oneline --allASCII graph showing branch relationships and merge points.
Filter by author:
git log --author="John Doe"
git log --author="john@example.com"Filter by date:
git log --since="2025-01-01"
git log --until="2025-06-01"
git log --since="2 weeks ago"
git log --since="3 days ago"Filter by commit message:
git log --grep="bug fix"
git log --grep="feature" -i # Case-insensitiveShow file changes in commits:
git log --stat # Show files changed
git log -p # Show full diff
git log -p filename.txt # Show changes to specific fileCustom format:
git log --pretty=format:"%h - %an, %ar : %s"
git log --pretty=format:"%C(yellow)%h%C(reset) %C(blue)%an%C(reset) %s"Format placeholders:
%h- Abbreviated commit hash%an- Author name%ar- Author date, relative%s- Commit subject%C(color)- Color output
Show specific commit:
git show abc123
git show HEAD # Show last commit
git show HEAD~2 # Show 2 commits backFind who changed each line:
git blame filename.txt
git blame -L 10,20 filename.txt # Only lines 10-20Commit Management
Undo last commit (keep changes):
git reset --soft HEAD~1Undo last commit (discard changes):
git reset --hard HEAD~1Undo commit by creating inverse commit:
git revert abc123Creates a new commit that undoes the changes from commit abc123. Safer than reset for public branches.
View reflog (command history):
git reflogShows every change to HEAD, including deleted commits. Lifesaver for recovering "lost" work.
Recover deleted commit:
git reflog # Find commit hash
git checkout -b recovery-branch abc123Tags
Tags mark important points in history, like releases.
List all tags:
git tag
git tag -l "v1.*" # Filter tags matching patternCreate lightweight tag:
git tag v1.0.0Create annotated tag (recommended):
git tag -a v1.0.0 -m "Release version 1.0.0"Annotated tags store author, date, and message.
Tag a specific commit:
git tag v0.9.0 abc123Show tag information:
git show v1.0.0Delete local tag:
git tag -d v1.0.0Delete remote tag:
git push origin --delete v1.0.0
git push origin :refs/tags/v1.0.0 # Alternative syntaxPush tags to remote:
git push origin v1.0.0 # Push specific tag
git push origin --tags # Push all tagsStashing
Stashing temporarily saves uncommitted changes, perfect for switching contexts quickly.
Save current changes:
git stash
git stash save "Work in progress on login feature"Include untracked files:
git stash save -u "Include new files"List all stashes:
git stash listOutput example:
stash@{0}: WIP on feature-login: abc123 Add validation
stash@{1}: On main: def456 Experiment with APIApply most recent stash:
git stash apply # Keep stash in list
git stash pop # Apply and remove from listApply specific stash:
git stash apply stash@{1}
git stash pop stash@{1}View stash contents:
git stash show # Summary
git stash show -p # Full diff
git stash show stash@{1} # Specific stashDelete specific stash:
git stash drop stash@{1}Delete all stashes:
git stash clearCreate branch from stash:
git stash branch new-feature stash@{0}Creates a branch and applies the stash to it.
Cherry-Picking and Patches
Sometimes you need to apply specific commits without a full merge.
Cherry-Picking
Apply specific commit to current branch:
git cherry-pick abc123Cherry-pick multiple commits:
git cherry-pick abc123 def456 ghi789Cherry-pick a range of commits:
git cherry-pick abc123..def456Cherry-pick without committing:
git cherry-pick -n abc123
git cherry-pick --no-commit abc123Stages the changes but doesn't commit, letting you modify before committing.
Abort cherry-pick:
git cherry-pick --abortContinue after resolving conflicts:
git cherry-pick --continueCreating and Applying Patches
Generate patch file:
git format-patch abc123 # Patch for commits after abc123
git format-patch -1 abc123 # Patch for single commit
git format-patch HEAD~3 # Last 3 commitsApply patch:
git apply patch-file.patch # Apply but don't commit
git am patch-file.patch # Apply and commitCheck if patch applies cleanly:
git apply --check patch-file.patchAdvanced Operations
Submodules
Submodules let you include other Git repositories within your project.
Add submodule:
git submodule add https://github.com/user/library.git libs/libraryInitialize submodules after cloning:
git submodule update --init --recursiveUpdate submodules to latest:
git submodule update --remoteRun command in all submodules:
git submodule foreach 'git pull origin main'Bisecting (Binary Search for Bugs)
Find which commit introduced a bug using binary search.
Start bisecting:
git bisect startMark current state as bad:
git bisect badMark a known good commit:
git bisect good abc123Git automatically checks out the midpoint commit. Test your code, then:
git bisect good # If this commit works
git bisect bad # If this commit has the bugRepeat until Git identifies the problematic commit.
End bisecting session:
git bisect resetAutomate with a test script:
git bisect start
git bisect bad HEAD
git bisect good v1.0.0
git bisect run npm testGit runs the test at each commit and automatically finds the bad commit.
Repository Maintenance
Verify repository integrity:
git fsckChecks for corrupted objects.
Optimize repository:
git gcGarbage collects unreachable objects and optimizes storage.
Aggressive optimization:
git gc --aggressive --prune=nowRemove untracked files:
git clean -n # Dry run (preview)
git clean -f # Remove files
git clean -fd # Remove files and directories
git clean -fdx # Remove files, directories, and ignored filesSearch for text in tracked files:
git grep "function" # Search all files
git grep "TODO" -- "*.js" # Search only JS files
git grep -n "error" # Show line numbersCollaboration Workflows
Pull Requests and Code Review
Generate pull request summary:
git request-pull v1.0 https://github.com/user/repo.git feature-branchCreates a summary of changes suitable for pull request descriptions.
Show author contributions:
git shortlog
git shortlog -sn # Summary with commit counts
git shortlog --since="6 months ago"List tracked files:
git ls-files
git ls-files --others # Untracked files
git ls-files --ignored # Ignored filesUseful Workflow Commands
Stash, pull, pop (safe update):
git stash
git pull
git stash popUndo local changes to specific file:
git checkout -- filename.txt
git restore filename.txt # Modern alternativeUnstage file:
git reset HEAD filename.txt
git restore --staged filename.txt # Modern alternativeDiscard all local changes:
git reset --hard HEADView file from another branch:
git show feature-branch:path/to/file.txtFind commits that add/remove text:
git log -S "function_name"Useful for finding when a function was added or removed.
Common Workflows and Best Practices
Feature Branch Workflow
- . Create feature branch:
git checkout -b feature-user-auth2. Make changes and commit:
git add .
git commit -m "Add user authentication"3. Push to remote:
git push -u origin feature-user-auth4. Create pull request on GitHub/GitLab
5. After review, merge and cleanup:
git checkout main
git pull
git branch -d feature-user-auth
git push origin --delete feature-user-authFixing Mistakes
Undo last commit but keep changes:
git reset --soft HEAD~1Change last commit message:
git commit --amend -m "Corrected message"Forgot to add file to last commit:
git add forgotten-file.txt
git commit --amend --no-editAccidentally committed to wrong branch:
git reset --soft HEAD~1
git stash
git checkout correct-branch
git stash pop
git add .
git commit -m "Message"Clean Commit History
Squash last 3 commits:
git rebase -i HEAD~3In the editor, change pick to squash for commits you want to combine.
Remove sensitive data from history:
git filter-branch --tree-filter 'rm -f passwords.txt' HEAD
git push --forceBetter alternative (modern):
git filter-repo --path passwords.txt --invert-paths(Requires git-filter-repo tool)
Git Configuration Tips
Useful Global Settings
Automatically rebase on pull: git config --global pull.rebase true
Use shorter status output: git config --global status.short true
Always show diff when committing: git config --global commit.verbose true
Auto-correct typos: git config --global help.autocorrect 1
Set default branch name: git config --global init.defaultBranch main
Better diff algorithm: git config --global diff.algorithm histogram
Useful Aliases
Add these to ~/.gitconfig:
[alias]
# Short status
s = status -s
# Pretty log
l = log --graph --pretty=format:'%C(yellow)%h%C(reset) -%C(red)%d%C(reset) %s %C(green)(%cr) %C(bold blue)<%an>%C(reset)' --abbrev-commit
# Show last commit
last = log -1 HEAD
# Unstage file
unstage = reset HEAD --
# Show changes to be committed
staged = diff --cached
# Amend without editing message
amend = commit --amend --no-edit
# Checkout
co = checkout
# Branch
br = branch
# Commit
ci = commit
# List aliases
aliases = config --get-regexp aliasQuick Reference Summary
Most-Used Commands
Daily workflow
git status
git add .
git commit -m "Message"
git pushBranch management
git checkout -b new-branch
git merge feature-branch
git branch -d old-branchSyncing
git fetch
git pull
git pushViewing history
git log --oneline
git diffUndoing changes
git reset --soft HEAD~1
git checkout -- file.txt
git revert abc123When Things Go Wrong
Lost work?
git reflogMerge conflicts?
git merge --abort
git statusFix conflicts, then:
git add .
git commitAccidentally committed?
git reset --soft HEAD~1Need to start over?
git reset --hard HEADRemote rejected push?
git pull --rebase
git pushKey Takeaways
- . Commit often: Small, focused commits are easier to review and revert
2. Use branches: Never work directly on main/master in collaborative projects
3. Write clear messages: Future you will thank present you
4. Pull before push: Always sync with remote before pushing changes
5. Learn rebasing: Keeps history clean and linear
6. Use stash: Switch contexts without committing half-done work
7. Explore reflog: Your safety net for "deleted" commits
8. Set up aliases: Save time on frequently-used commands
9. Read the docs: git help <command> is your friend
10. Practice in test repos: Experiment fearlessly before trying advanced operations on production code
Git mastery takes time, but having this reference at your fingertips accelerates the learning process. Bookmark this page and return whenever you need a quick reminder. The more you use these commands, the more they'll become second nature.
Happy versioning!