🔧 Git Command Cheat Sheet DevOps Quick Reference • All Essential Commands
← All articles
⚙️ Setup & Config
git config --global user.name "Name"Set global username
git config --global user.email "x@y"Set global email
git config --global init.defaultBranch mainDefault branch = main
git config --global core.editor "code --wait"Set VS Code as editor
git config --global color.ui autoEnable colored output
git config --global pull.rebase truePull with rebase by default
git config --listView all settings
git config user.nameView a specific setting
git config --global alias.lg "log ..."Create shortcut alias
📁 Repository
git initInit new repo in current dir
git init <name>Init in new folder
git clone <url>Clone remote repo locally
git clone --depth=1 <url>Shallow clone (latest only)
git clone <url> <folder>Clone into specific folder
git remote -vList configured remotes
git remote add origin <url>Add a remote
git remote set-url origin <url>Change remote URL
git remote rename origin upstreamRename a remote
git remote remove <name>Remove a remote
📊 Status & Inspect
git statusShow working tree status
git status -sShort / compact status
git log --onelineCompact commit history
git log --oneline --graph --allVisual branch graph
git log -5Last 5 commits
git log --author="Name"Commits by author
git log --since="1 week ago"Commits in last week
git log --grep="bugfix"Search commit messages
git show <hash>Show details of a commit
git diffUnstaged changes
git diff --stagedStaged vs last commit
git diff main..featureDiff between branches
git diff --name-onlyOnly filenames changed
git blame <file>Line-by-line authorship
git shortlog -snCommit count by author
✏️ Stage & Commit
Staging
git add <file>Stage a single file
git add .Stage all changes
git add -uStage tracked files only
git add -p <file>Stage hunks interactively
git restore --staged <file>Unstage a file
git restore <file>Discard working dir changes
Committing
git commit -m "msg"Commit with message
git commit -am "msg"Stage tracked + commit
git commit --amendFix last commit (pre-push!)
git commit --amend --no-editAdd files to last commit
Stash
git stashStash uncommitted work
git stash push -m "note"Stash with description
git stash listView all stashes
git stash popRestore and remove latest
git stash apply stash@{n}Apply specific stash
git stash branch <name>Create branch from stash
git stash drop / clearDelete stash(es)
🌿 Branches
Managing Branches
git branchList local branches
git branch -aList all (local + remote)
git branch -vLast commit on each
git branch --mergedShow merged branches
git checkout -b <name>Create & switch branch
git switch -c <name>Modern: create & switch
git switch <name>Switch existing branch
git branch -m old newRename a branch
git branch -d <branch>Delete merged branch
git branch -D <branch>Force delete branch
Merging
git merge --no-ff <branch>Merge with merge commit
git merge --abortAbort in-progress merge
git checkout --ours <file>Keep our version in conflict
git checkout --theirs <file>Keep their version
Rebase
git rebase mainRebase onto main
git rebase -i HEAD~3Interactive rebase (last 3)
git rebase --continueContinue after conflict fix
git rebase --abortAbort rebase
🔁 Sync with Remote
Pushing
git push -u origin mainPush + set tracking
git pushPush (tracking already set)
git push -u origin <branch>Push new branch to remote
git push --tagsPush all tags
git push origin --delete <br>Delete remote branch
Fetching & Pulling
git fetch originDownload (no merge)
git fetch --allFetch from all remotes
git pullFetch + merge
git pull --rebaseFetch + rebase (cleaner)
git pull origin mainPull specific branch
↩️ Undo & Recover
Safe Undos
git restore <file>Discard file changes
git restore --staged <file>Unstage a file
git revert <hash>Safe undo (new commit)
git reset (careful!)
git reset --soft HEAD~1Undo commit, keep staged
git reset HEAD~1Undo commit, keep files
git reset --hard HEAD~1⚠ Undo + DISCARD all
git reset --hard <hash>⚠ Reset to specific commit
Recovery
git reflogView ALL HEAD movements
git checkout -b recover <hash>Restore from reflog hash
git cherry-pick <hash>Apply specific commit here
git cherry-pick h1^..h2Cherry-pick a range
Bug Hunting
git bisect startStart binary search
git bisect bad / goodMark current as bad/good
git bisect resetEnd bisect session
🔖 Tags & Releases
git tagList all tags
git tag -a v1.0.0 -m "msg"Annotated tag (recommended)
git tag v1.0.0Lightweight tag
git tag -a v0.9 abc123 -m "msg"Tag a past commit
git push origin v1.0.0Push single tag
git push --tagsPush all tags
git tag -d v1.0.0Delete local tag
git push origin --delete v1.0.0Delete remote tag
git checkout v1.0.0Check out at tag (detached)
🚀 Advanced
Hooks
ls .git/hooks/List available hooks
chmod +x .git/hooks/pre-commitEnable a hook script
Cleaning
git clean -fdRemove untracked files+dirs
git clean -nDry run (preview only)
Utilities
git archive --format=zip HEADExport repo as ZIP
git submodule add <url>Add a submodule
git log -p -- <file>History of a specific file
git log --diff-filter=D -- <f>Find deleted files
git grep "pattern"Search working tree
git check-ignore -v <file>Why is file ignored?
Aliases (add to ~/.gitconfig)
alias.st statusgit st → git status
alias.co checkoutgit co → git checkout
alias.lg "log --oneline --graph --all"git lg → visual graph
🔄 Git Three-Zone Flow
✏️
Working Dir
Edit files
git add
📋
Staging Area
Index
git commit
🗄️
Local Repo
.git folder
git push
☁️
Remote
GitHub/GitLab
Reverse: git fetch / pull ← Remote  |  git checkout ← Local Repo  |  git restore ← Staging
Daily Developer Workflow
1
git pull --rebase — sync with remote first
2
git checkout -b feature/xxx — create branch
3
Code → git add .git commit -m "feat: ..."
4
git push -u origin feature/xxx — push branch
5
Open Pull Request on GitHub / GitLab
6
Code review + CI passes → merge PR
7
git checkout main && git pull — update local
8
git branch -d feature/xxx — clean up
🚫 Never Do This on Shared Branches
git push --force
Overwrites remote history — breaks teammates' clones
git reset --hard on main
Permanently destroys commits — irrecoverable for others
git rebase on pushed branch
Rewrites history — everyone's branch diverges
git commit .env / secrets
Security breach — rotate immediately if this happens
git add . without checking diff
May stage build artifacts or sensitive files
git commit --amend after push
Creates diverged history — force push required
📝 Conventional Commits
Format: type(scope): description
feat:New feature for the user
fix:Bug fix for the user
docs:Documentation changes only
style:Formatting, no logic change
refactor:Code restructure, no feature/fix
test:Adding or fixing tests
chore:Build / config / tooling
ci:CI/CD pipeline changes
perf:Performance improvement
revert:Reverts a previous commit
Examples:
feat(auth): add OAuth2 Google sign-in
fix(api): handle null response from payment gateway
ci: add SAST scan to PR pipeline
🗺️ Branching Strategies
Git Flow — Release-based products
mainProduction only — always tagged
developIntegration branch for features
feature/xxxOne branch per feature from develop
release/x.y.zRelease prep — only bug fixes
hotfix/xxxEmergency fix from main
GitHub Flow — Continuous deployment
mainAlways deployable
feature/xxxBranch → PR → merge = deploy
Trunk-Based Dev — High-velocity teams
main (trunk)All devs commit multiple times/day
Feature flagsHide incomplete features in prod
Short branchesLive < 2 days; requires solid CI
🔧 Common Problems & Fixes
Frequent Issues
Committed to wrong branchgit reset --soft HEAD~1 → switch branch
Detached HEADgit checkout main OR git checkout -b <name>
Push rejectedgit pull --rebase, resolve, then push
Accidentally deleted branchgit reflog → find hash → git checkout -b name <hash>
Committed a secretRotate credential immediately + BFG Repo Cleaner
.gitignore not workinggit rm --cached <file> (file already tracked)
Large file blockedgit rm --cached + .gitignore + use Git LFS
Wrong commit authorgit commit --amend --author (before push)
Merge conflict binarygit checkout --ours/--theirs <file>