Home / Software / Git / Git Cheat Sheet: Every Command You Need

Git Cheat Sheet: Every Command You Need

Git Cheat Sheet: Every Command You Need

Git is a distributed version control system used by developers and IT professionals to track changes, collaborate on code, and manage project history. This page is a practical command reference for Git 2.x, covering everything from initial setup to advanced workflows. Commands are grouped by task so you can find what you need quickly during daily use.

Setup and Configuration

CommandWhat it doesNotes
git --versionShow installed Git versionConfirm Git is installed and check version
git config --global user.name "Your Name"Set your name for all commitsStored in ~/.gitconfig
git config --global user.email "[email protected]"Set your email for all commitsMust match your GitHub/GitLab account email
git config --global core.editor nanoSet default text editorUse vim, code --wait, or any editor
git config --global init.defaultBranch mainSet default branch name for new reposReplaces legacy master default
git config --listDisplay all current configurationAdd --global to show only global config
git config --global alias.st statusCreate a command aliasAfter this, git st runs git status
git config --global pull.rebase falseUse merge (not rebase) on pullSet to true to rebase on pull instead

Starting a Repository

CommandWhat it doesNotes
git initInitialise a new local repositoryCreates a .git directory in the current folder
git init --bareInitialise a bare repositoryUsed for server-side repos; no working tree
git clone URLClone a remote repositoryCreates a folder named after the repo
git clone URL foldernameClone into a specific folder nameOverrides the default folder name
git clone --depth 1 URLShallow clone — latest snapshot onlyFaster; omits full history. Good for CI pipelines
git clone --branch branchname URLClone and check out a specific branchAlso accepts tag names

Staging and Committing

CommandWhat it doesNotes
git statusShow working tree and staging area statusUse frequently; shows what is staged, unstaged, untracked
git add fileStage a specific fileSupports glob patterns, e.g. git add *.js
git add .Stage all changes in current directoryIncludes new, modified, and deleted files
git add -pInteractively stage chunks of changesLets you stage partial file changes — very useful for clean commits
git diffShow unstaged changesCompares working directory to staging area
git diff --stagedShow staged changesCompares staging area to last commit
git commit -m "message"Commit staged changes with a messageKeep messages concise and in the imperative tense
git commit -am "message"Stage all tracked changes and commitSkips git add — does not include new untracked files
git commit --amendAmend the last commitOpens editor to change message and/or staged content
git commit --amend --no-editAmend last commit without changing the messageUseful to add a forgotten file to the previous commit

Branching

CommandWhat it doesNotes
git branchList local branchesCurrent branch is highlighted with *
git branch -aList all branches including remote-trackingRemote branches shown as remotes/origin/name
git branch branchnameCreate a new branchDoes not switch to it; use checkout -b or switch -c to create and switch
git checkout branchnameSwitch to an existing branchClassic syntax; also used to check out files
git checkout -b branchnameCreate and switch to a new branchEquivalent to git branch + git checkout
git switch branchnameSwitch to a branch (modern syntax)Introduced in Git 2.23; preferred over checkout for switching
git switch -c branchnameCreate and switch to a new branch (modern syntax)Modern equivalent of git checkout -b
git branch -d branchnameDelete a branch (safe)Only deletes if fully merged
git branch -D branchnameForce-delete a branchDeletes regardless of merge status
git branch -m oldname newnameRename a branchRename the current branch with git branch -m newname
git merge branchnameMerge a branch into the current branchFast-forwards if possible
git merge --no-ff branchnameMerge and always create a merge commitPreserves branch history even when fast-forward is possible
git rebase branchnameRebase current branch onto anotherRewrites history — avoid on shared branches

Remote Repositories

CommandWhat it doesNotes
git remote -vList remotes with URLsShows fetch and push URLs
git remote add origin URLAdd a remote named originorigin is convention; any name can be used
git remote remove nameRemove a remoteDoes not delete the remote repository itself
git remote rename old newRename a remotee.g. git remote rename origin upstream
git remote set-url origin URLChange the URL of a remoteUseful when switching from HTTPS to SSH
git fetchDownload changes from remote without mergingSafe — does not modify working tree
git fetch --allFetch from all remotesUseful in multi-remote setups
git pullFetch and merge remote changes into current branchEquivalent to git fetch + git merge
git pull origin branchnamePull a specific remote branchMerges into your current branch
git pushPush current branch to its tracked remoteRequires upstream to be set
git push origin branchnamePush a specific branch to remoteCreates the branch on remote if it does not exist
git push -u origin branchnamePush and set upstream trackingAfter this, plain git push works for this branch
git push --force-with-leaseForce push safelyFails if the remote has commits you have not fetched — safer than --force
git push origin --delete branchnameDelete a branch on the remoteDoes not delete the local branch

Viewing History

CommandWhat it doesNotes
git logShow full commit historyPress q to exit the pager
git log --onelineShow condensed one-line historyShows short hash and subject line
git log --oneline --graph --allShow branch graph for all branchesAdd --decorate to include branch and tag labels
git log -n 10Show only the last 10 commitsReplace 10 with any number
git log --since="2 weeks ago"Show commits from the past two weeksAlso accepts --until, dates, and relative strings
git log --author="Name"Filter commits by authorPartial name or email matches work
git log -- filenameShow commits that changed a specific fileThe -- separator is good practice
git log -pShow commits with their diffsVerbose — combine with -n to limit output
git show COMMITShow details and diff for a specific commitUse short hash, full hash, or tag name
git diff COMMIT1 COMMIT2Show differences between two commitsUse branch names or hashes
git blame filenameShow who last changed each line of a fileAdd -L 10,20 to limit to a line range
git shortlog -snSummary of commits per contributor-s suppresses messages, -n sorts by count

Undoing Changes

Safe — does not rewrite history

CommandWhat it doesNotes
git restore fileDiscard working directory changes to a fileIrreversible — changes are lost. Replaces old git checkout -- file
git restore --staged fileUnstage a fileKeeps changes in working directory
git revert COMMITCreate a new commit that undoes a previous commitSafe for shared branches — history is preserved
git stashStash current uncommitted changesCleans working tree; changes can be restored later
git stash popRestore most recent stash and remove itApplies stash and drops it from the stash list
git stash listList all stashed entriesEntries shown as stash@{0}, stash@{1}, etc.
git stash dropDelete the most recent stash entryUse git stash drop stash@{n} for a specific entry

Destructive — rewrites history. Use with care on shared branches

CommandWhat it doesNotes
git reset --soft HEAD~1Undo last commit; keep changes stagedCommit is removed; all changes remain ready to recommit
git reset --mixed HEAD~1Undo last commit; keep changes unstagedDefault mode if no flag is specified
git reset --hard HEAD~1Undo last commit and discard all changesPermanent data loss — cannot be undone without the reflog
git reset --hard origin/mainReset local branch to match remote exactlyDestroys all local commits and changes not on the remote
git clean -fdDelete all untracked files and directoriesRun git clean -nfd first for a dry run

Stashing

CommandWhat it doesNotes
git stashStash tracked changesAdd -u to also stash untracked files
git stash save "message"Stash with a descriptive labelMakes stash list easier to read
git stash listList all stash entriesShows index, branch, and message
git stash show stash@{0}Show summary of a stash entryAdd -p for full diff
git stash popApply most recent stash and remove itEquivalent to apply + drop
git stash apply stash@{0}Apply a specific stash without removing itStash entry remains in the list
git stash drop stash@{0}Delete a specific stash entryPermanently removes it from the list
git stash clearDelete all stash entriesIrreversible
git stash branch newbranchCreate a new branch from the stashApplies stash and drops it if successful

Tags

CommandWhat it doesNotes
git tagList all tagsAdd -l "v1.*" to filter by pattern
git tag v1.0.0Create a lightweight tag at HEADLightweight tags are just pointers; no metadata
git tag -a v1.0.0 -m "message"Create an annotated tagStores tagger name, date, and message — preferred for releases
git tag -a v1.0.0 COMMITTag a specific past commitReplace COMMIT with the hash
git push origin v1.0.0Push a single tag to remoteTags are not pushed automatically with git push
git push origin --tagsPush all local tags to remotePushes all tags not yet on the remote
git tag -d v1.0.0Delete a tag locallyDoes not affect the remote
git push origin --delete v1.0.0Delete a tag from the remoteYou must also delete locally with git tag -d

Searching

CommandWhat it doesNotes
git grep "searchterm"Search working tree for a stringFaster than grep on large repos; respects .gitignore
git log --all --grep="message"Search commit messages across all branchesCase-insensitive with -i
git log -S "code string"Find commits that added or removed a stringKnown as the “pickaxe” search; useful for tracking when code appeared
git bisect startBegin a binary search for a bug-introducing commitThen mark commits as git bisect bad or git bisect good COMMIT
git bisect badMark current commit as containing the bugGit will check out a midpoint commit to test next
git bisect good COMMITMark a known-good commitProvide the last commit you know was working

Submodules

CommandWhat it doesNotes
git submodule add URL pathAdd a repository as a submoduleCreates .gitmodules and stages changes
git submodule initInitialise submodules listed in .gitmodulesRun after cloning a repo with submodules
git submodule updateCheck out submodules at their recorded commitRun after git submodule init
git submodule update --init --recursiveInitialise and update all nested submodulesSingle command for freshly cloned repos with submodules
git submodule foreach git pull origin mainRun a command in every submoduleAny Git command can follow foreach
git submodule statusShow the current state of all submodulesPrefix - means uninitialised, + means different from recorded commit

.gitignore Quick Reference

A .gitignore file tells Git which files and directories to ignore. Place it in the repository root. Lines starting with # are comments. A trailing / matches directories only. A leading ! negates a pattern.

# Ignore a specific file
secrets.env

# Ignore a directory
node_modules/
.venv/

# Ignore all .log files
*.log

# Ignore all .log files except one
*.log
!important.log

# Ignore in any subdirectory
**/temp/

Common .gitignore entries

EntryWhat it ignores
node_modules/Node.js dependencies directory
.envEnvironment variable files containing secrets
.venv/Python virtual environment directory
__pycache__/Python compiled bytecode cache
*.pycCompiled Python files
.DS_StoremacOS Finder metadata files
Thumbs.dbWindows Explorer thumbnail cache
*.logLog files
dist/Build output directory (JavaScript/Python)
build/Compiled build output
.idea/JetBrains IDE project files
.vscode/Visual Studio Code workspace settings

Git Aliases (Time Savers)

Add these aliases to your global Git configuration to speed up common workflows. Once set, the short form works in any repository.

git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.lg "log --oneline --graph --all --decorate"
git config --global alias.undo "reset --soft HEAD~1"
git config --global alias.unstage "restore --staged"

After running the above, you can use git st, git co, git lg, git undo, and git unstage directly.

SSH Keys for GitHub/GitLab

SSH authentication is more secure than HTTPS with a password and avoids repeated credential prompts. Generate a key once per machine, add the public key to your account, then update your remotes to use SSH URLs.

# Generate an ED25519 key (recommended)
ssh-keygen -t ed25519 -C "[email protected]"

# Print the public key to copy into GitHub / GitLab
cat ~/.ssh/id_ed25519.pub

# Test connection to GitHub
ssh -T [email protected]

# Use SSH instead of HTTPS for an existing remote
git remote set-url origin [email protected]:user/repo.git

Useful One-Liners

# Show all branches sorted by most recent commit
git branch -a --sort=-committerdate
# Find which branch(es) contain a specific commit
git branch --contains COMMIT
# List files changed in the last commit
git diff-tree --no-commit-id -r --name-only HEAD
# Squash the last 3 commits into one
git reset --soft HEAD~3 && git commit -m "Squashed commit"
# Cherry-pick a single commit from another branch
git cherry-pick COMMIT
# Preview what would be pushed to the remote
git log origin/main..HEAD --oneline
# Export a file at a specific commit to a new file
git show COMMIT:path/to/file > output.txt
# Stop tracking a file without deleting it locally
git rm --cached filename

Related articles: n8n Expressions Cheat Sheet: Variables, Functions and Syntax, Proxmox Cheat Sheet: CLI Commands for VMs, LXC and Storage, Linux Commands Cheat Sheet: Home Lab and Server Reference