Cheatsheets

Git

Git

Git is a distributed version control system for tracking code changes, collaborating with teams, and managing project history.

8 Categories 19 Sections 37 Examples
Git Version Control Branches Commits Collaboration SCM GitHub GitLab

Getting Started

Initialize repositories and configure Git for your first use.

Git Configuration

Set up your Git identity and configure global preferences.

Set user identity

Sets the name and email used for commit authorship. Use --global for all repositories or --local for specific project.

Code
Terminal window
# Configure user name and email
git config --global user.name "John Doe"
git config --global user.email "john@example.com"
# Configure for specific project only
git config --local user.name "John Doe"
git config --local user.email "john@example.com"
Execution
Terminal window
git config --global user.name
Output
Terminal window
John Doe
  • Global config is stored in ~/.gitconfig
  • Local config overrides global settings
  • Required before making your first commit

Configure editor and defaults

Customize Git behavior with editor preferences, default branch naming, and line ending handling.

Code
Terminal window
# Set default editor for commits
git config --global core.editor "nano"
# Set default branch name for new repositories
git config --global init.defaultBranch "main"
# Configure line ending handling
git config --global core.autocrlf true
Execution
Terminal window
git config --global --list
Output
Terminal window
user.name=John Doe
user.email=john@example.com
core.editor=nano
init.defaultBranch=main
  • autocrlf: true (Windows), input (Unix/macOS)
  • View all config with --list flag

Initialize and Clone

Create new repositories locally or clone existing ones.

Initialize a new repository

Creates a new Git repository in current directory with a hidden .git folder containing repository metadata.

Code
Terminal window
# Create new directory and initialize git
mkdir my-project
cd my-project
git init
# Or initialize git in existing directory
cd existing-directory
git init
# Initialize with specific default branch
git init --initial-branch=main
Execution
Terminal window
git init
Output
Terminal window
Initialized empty Git repository in /path/to/repo/.git/
  • Creates .git directory with Git internals
  • Safe to run multiple times
  • Default branch is master or configurable as main

Clone a remote repository

Clones a remote repository to your local machine, including full history and all branches.

Code
Terminal window
# Clone with HTTPS
git clone https://github.com/user/repo.git
# Clone with SSH
git clone git@github.com:user/repo.git
# Clone into specific directory
git clone https://github.com/user/repo.git my-folder
# Clone with limited history
git clone --depth 1 https://github.com/user/repo.git
Execution
Terminal window
git clone https://github.com/user/repo.git
Output
Terminal window
Cloning into 'repo'...
remote: Counting objects: 100%
Receiving objects: 100% (150/150), 25.5 KiB | 500 KiB/s
Resolving deltas: 100% (50/50), done.
  • --depth 1 for shallow clone (faster, less history)
  • Creates directory with repo name by default
  • SSH requires key setup, HTTPS uses credentials

Basic Commands

Essential commands for daily Git workflow.

Staging and Committing

Add changes to staging area and create commits.

Stage and commit changes

Adds modified files to staging area and creates a commit with descriptive message.

Code
Terminal window
# Check status of repository
git status
# Stage specific file
git add filename.txt
# Stage all changes
git add .
# Commit staged changes
git commit -m "Add new feature"
# Stage and commit in one command
git commit -am "Fix bug"
Execution
Terminal window
git add . && git commit -m "Update code"
Output
Terminal window
[main a1b2c3d] Update code
3 files changed, 45 insertions(+), 10 deletions(-)
  • git add stages changes for commit
  • git commit creates snapshot with message
  • -m flag for inline commit message
  • -a flag skips staging for tracked files

Amend commits

Modifies the most recent commit by adding changes or changing the message.

Code
Terminal window
# Add forgotten file to previous commit
git add forgotten_file.txt
git commit --amend --no-edit
# Change commit message
git commit --amend -m "Better message"
# Amend without changing message
git commit --amend --no-edit
# Amend with timestamp update
git commit --amend --date now
Execution
Terminal window
git commit --amend -m "Updated message"
Output
Terminal window
[main 5d4e3c2] Updated message
Date: Fri Feb 28 2025 10:30:00
2 files changed, 50 insertions(+)
  • Only amend unpushed commits to avoid conflicts
  • --no-edit keeps original message
  • Useful for fixing small mistakes before pushing

Push and Pull

Synchronize changes with remote repositories.

Push changes to remote

Uploads local commits to the remote repository on the specified branch.

Code
Terminal window
# Push current branch to remote
git push
# Push to specific remote and branch
git push origin main
# Push all local branches
git push origin --all
# Push with force (only if needed)
git push --force-with-lease
# Push specific tag
git push origin v1.0.0
Execution
Terminal window
git push origin main
Output
Terminal window
Enumerating objects: 5, done.
Writing objects: 100% (3/3), 280 bytes
To github.com:user/repo.git
a1b2c3d..x8y9z0a main -> main
  • Default remote is usually 'origin'
  • First push may require --set-upstream
  • Use --force-with-lease instead of --force

Pull changes from remote

Downloads and integrates remote changes into the current branch.

Code
Terminal window
# Fetch and merge remote changes
git pull
# Pull from specific remote and branch
git pull origin main
# Pull with rebase instead of merge
git pull --rebase
# Fetch only (don't merge)
git fetch
# Fetch from all remotes
git fetch --all
Execution
Terminal window
git pull origin main
Output
Terminal window
From github.com:user/repo
* branch main -> FETCH_HEAD
Fast-forward
file.txt | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
  • git pull = git fetch + git merge
  • Use --rebase for linear history
  • Always pull before pushing to avoid conflicts

View Status and History

Check repository status and view change history.

Check repository status

Shows which files are modified, staged, or untracked in current working directory.

Code
Terminal window
# View current status
git status
# Short status format
git status -s
# Include untracked files
git status --include-untracked
Execution
Terminal window
git status -s
Output
Terminal window
M config.js
A new-file.txt
?? untracked.txt
  • M = modified, A = added, ?? = untracked
  • First letter = staging area, second = working directory

View differences in files

Shows line-by-line differences between working directory and staging area or between commits.

Code
Terminal window
# View unstaged changes
git diff
# View staged changes
git diff --staged
# View changes in specific file
git diff filename.txt
# View changes between commits
git diff HEAD~2 HEAD
Execution
Terminal window
git diff --staged
Output
Terminal window
diff --git a/file.txt b/file.txt
index 1234567..abcdefg 100644
--- a/file.txt
+++ b/file.txt
@@ -5,7 +5,7 @@
old content
-removed line
+added line
  • Plus sign (+) for added lines
  • Minus sign (-) for removed lines
  • Use --color-words for word-level diff

Branches

Create, manage, and work with branches for parallel development.

Create and Delete Branches

Create new branches and delete obsolete ones.

Create and switch branches

Creates a new branch either from current HEAD or specific commit and optionally switches to it.

Code
Terminal window
# Create new branch
git branch feature-new
# Create and switch in one command
git checkout -b feature-new
# Create branch from specific commit
git branch feature-new a1b2c3d
# Create tracking branch
git branch --track feature origin/feature
# Create branch with no upstream
git branch --no-track feature-local
Execution
Terminal window
git checkout -b feature-new
Output
Terminal window
Switched to a new branch 'feature-new'
  • Branch name should use hyphens, not spaces
  • New branch contains all commits up to creation point
  • Use descriptive names (feature/*, fix/*, etc)

Delete branches

Removes branches locally or from remote repository. -d is safe, -D forces deletion.

Code
Terminal window
# Delete local branch (safe)
git branch -d feature-new
# Force delete unmerged branch
git branch -D feature-new
# Delete remote branch
git push origin --delete feature-new
# Delete multiple branches
git branch -d feature-1 feature-2 feature-3
Execution
Terminal window
git branch -d feature-new
Output
Terminal window
Deleted branch feature-new (was a1b2c3d).
  • -d prevents deleting unmerged branches
  • -D forces deletion regardless of merge status
  • Deleting remote branch pushes deletion to origin

Switch and Merge Branches

Switch between branches and merge changes.

Switch between branches

Changes working directory to selected branch. Can create new branch at same time.

Code
Terminal window
# Switch to existing branch
git checkout main
# Create and switch in one command
git checkout -b feature
# Switch using new syntax
git switch main
# Create and switch with new syntax
git switch -c feature
# Return to previous branch
git checkout -
Execution
Terminal window
git switch main
Output
Terminal window
Switched to branch 'main'
  • git switch is newer, alias for checkout
  • Saved uncommitted changes before switching
  • Use - to switch to previously checked out branch

Merge branches

Integrates commits from another branch into the current branch. Fast-forward if possible.

Code
Terminal window
# Merge feature branch into current branch
git merge feature
# Merge with no fast-forward
git merge --no-ff feature
# Squash commits before merging
git merge --squash feature
# Abort merge if conflicts
git merge --abort
Execution
Terminal window
git merge feature
Output
Terminal window
Merge made by the 'recursive' strategy.
file.txt | 5 +++--
1 file changed, 2 insertions(+), 3 deletions(-)
  • Merge creates merge commit if no fast-forward possible
  • --no-ff always creates merge commit
  • --squash combines all commits into single commit

List and Compare Branches

View and compare branches in repository.

List branches

Lists all branches with option to show last commit for each branch.

Code
Terminal window
# List local branches
git branch
# List with last commit info
git branch -v
# List remote branches
git branch -r
# List all branches (local and remote)
git branch -a
# List merged branches
git branch --merged
# List unmerged branches
git branch --no-merged
Execution
Terminal window
git branch -v
Output
Terminal window
* main a1b2c3d Update README
feature x8y9z0a Add new feature
bugfix p5q6r7s Fix critical bug
  • Asterisk (*) marks current branch
  • -r shows remote branches
  • -a shows both local and remote

Logs & History

View, search, and analyze commit history.

View Commit History

Display commit history with various formats and filters.

View commit history

Shows commit history in selected format. Use --oneline for concise view, --graph for branch visualization.

Code
Terminal window
# View commit history
git log
# View in one-line format
git log --oneline
# View with branch graph
git log --graph --all --oneline --decorate
# View recent commits
git log -n 5
# View with statistics
git log --stat
Execution
Terminal window
git log --oneline -n 5
Output
Terminal window
a1b2c3d Update documentation
x8y9z0a Add authentication
p5q6r7s Fix login bug
m3n4o5p Refactor database
i1j2k3l Initial commit
  • Without arguments shows full commit info
  • --stat shows file changes per commit
  • --graph helps visualize branching

Filter and format logs

Filters log by author, date range, or custom format for precise history searching.

Code
Terminal window
# View commits by author
git log --author="John Doe"
# View commits since date
git log --since="2025-01-01"
# View commits until date
git log --until="2025-02-01"
# Custom format
git log --pretty=format:"%h %s by %an"
# View specific file history
git log -- filename.txt
Execution
Terminal window
git log --author="John" --oneline --graph
Output
Terminal window
* a1b2c3d Update code
* x8y9z0a Fix bug
* p5q6r7s Add feature
  • Useful for tracking specific changes
  • Custom format strings available in docs
  • Filter by file to track changes in specific files

Advanced Log Filtering

Use revisions and ranges to explore commit history.

Reference commits with revisions

Shows specific commits using HEAD references and relative positioning.

Code
Terminal window
# HEAD references
git show HEAD # Most recent commit
git show HEAD~1 # One commit before HEAD
git show HEAD~2 # Two commits before HEAD
git show HEAD^ # Parent of HEAD
git show HEAD^^ # Grandparent of HEAD
# Show specific commit
git show a1b2c3d
# Show commit from tag
git show v1.0.0
Execution
Terminal window
git show HEAD~1
Output
Terminal window
commit a1b2c3d3f4g5h6i7j8k9l0m1n
Author: John Doe <john@example.com>
Date: Fri Feb 27 2025
Previous commit message
  • HEAD~n counts back n commits in history
  • HEAD^ refers to parent commit
  • Use with show, log, diff for detailed exploration

Use commit ranges

Shows commits within specified ranges, useful for comparing branches.

Code
Terminal window
# Commits in feature but not main (two-dot)
git log main..feature
# Commits in either branch (three-dot)
git log main...feature
# Commits reachable from branch
git log feature
# Commits in range
git log a1b2c3d..x8y9z0a
Execution
Terminal window
git log main..feature --oneline
Output
Terminal window
p5q6r7s Add feature implementation
m3n4o5p Update tests
  • Two-dot: commits in first branch only
  • Three-dot: commits in either branch, not both

Undoing Changes

Revert, reset, and restore changes in various scenarios.

Reset and Revert

Move HEAD and undo commits permanently or safely.

Reset changes

Moves HEAD to previous state. --soft keeps changes staged, --mixed unstages, --hard discards all.

Code
Terminal window
# Undo last commit, keep changes staged
git reset --soft HEAD~1
# Undo last commit, keep changes in working dir
git reset --mixed HEAD~1
# Discard last commit and all changes
git reset --hard HEAD~1
# Unstage file
git reset HEAD filename.txt
# Reset to specific commit
git reset --hard a1b2c3d
Execution
Terminal window
git reset --soft HEAD~1
  • DANGEROUS if commits pushed to shared branch
  • Use on local commits only
  • --hard irreversibly deletes changes

Safely revert commits

Creates new commit that undoes changes from specified commit. Safe for shared branches.

Code
Terminal window
# Create new commit reversing changes
git revert HEAD
# Revert specific commit
git revert a1b2c3d
# Revert multiple commits
git revert --no-edit HEAD~3..HEAD
# Revert without committing
git revert -n HEAD
Execution
Terminal window
git revert HEAD
Output
Terminal window
[main b3c4d5e] Revert "Add feature"
1 file changed, 10 deletions(-)
  • Creates new commit (preserve history)
  • Safe for pushed commits
  • Opposite changes in new commit

Restore and Checkout Files

Restore files to previous states without moving HEAD.

Discard changes in files

Restores files to their last committed state, discarding local changes.

Code
Terminal window
# Discard changes to file (checkout)
git checkout -- filename.txt
# Discard changes (restore)
git restore filename.txt
# Discard all changes
git restore .
# Restore from specific commit
git checkout a1b2c3d -- filename.txt
# Restore to previous version
git restore --source=HEAD~1 filename.txt
Execution
Terminal window
git restore filename.txt
  • Does not affect commit history
  • Useful for discarding accidental changes
  • --source specifies which commit to restore from

Unstage files

Removes files from staging area while keeping changes in working directory.

Code
Terminal window
# Unstage file (restore --staged)
git restore --staged filename.txt
# Unstage all files
git restore --staged .
# Alternative: reset
git reset HEAD filename.txt
# Unstage but keep changes
git reset HEAD filename.txt
Execution
Terminal window
git restore --staged filename.txt
  • Changes remain in working directory
  • Allows re-staging with modifications

Advanced

Complex operations for power users and advanced workflows.

Rebase and Cherry Pick

Rewrite history and apply selective commits.

Rebase branch over another

Replays commits on top of another branch creating linear history instead of merge.

Code
Terminal window
# Rebase current branch onto main
git rebase main
# Interactive rebase for last 3 commits
git rebase -i HEAD~3
# Rebase and squash commits
git rebase -i HEAD~3
# In editor: keep first 'pick', change others to 'squash'
# Abort rebase if problems
git rebase --abort
# Continue after resolving conflicts
git rebase --continue
Execution
Terminal window
git rebase main
Output
Terminal window
First, rewinding head to replay your work on top of it...
Applying: Add feature
Applying: Fix tests
  • Creates new commit objects (changes hashes)
  • Never rebase pushed commits in shared branches
  • Interactive rebase (-i) allows editing commits

Cherry pick commits

Applies changes from specific commit to current branch, creating new commit.

Code
Terminal window
# Apply specific commit to current branch
git cherry-pick a1b2c3d
# Pick multiple commits
git cherry-pick a1b2c3d x8y9z0a
# Pick range of commits
git cherry-pick a1b2c3d..x8y9z0a
# Cherry-pick without committing
git cherry-pick -n a1b2c3d
# Abort if conflicts
git cherry-pick --abort
Execution
Terminal window
git cherry-pick a1b2c3d
Output
Terminal window
[main p3q4r5s] Add feature
1 file changed, 25 insertions(+)
  • Useful for backporting fixes
  • Creates new commits (different hashes)
  • Resolve conflicts same as merge

Stash and Merge

Temporarily save work and integrate branches.

Stash changes

Temporarily saves uncommitted changes, cleaning working directory.

Code
Terminal window
# Stash current changes
git stash
# Stash with message
git stash save "my work in progress"
# Stash including untracked files
git stash -u
# List all stashes
git stash list
# Apply latest stash
git stash apply
# Apply and remove stash
git stash pop
# Apply specific stash
git stash apply stash@{0}
Execution
Terminal window
git stash
Output
Terminal window
Saved working directory and index state WIP on main: a1b2c3d Update docs
  • Stash stores changes in temporary storage
  • list shows all saved stashes
  • pop applies and removes stash

Handle merge conflicts

Handles merge conflicts by manual resolution and recommit.

Code
Terminal window
# Start merge (may hit conflicts)
git merge feature
# View conflicted files
git status
# View specific conflict
git diff
# After solving in editor:
git add resolved-file.txt
git commit -m "Merge feature branch"
# Abort merge if necessary
git merge --abort
Execution
Terminal window
git merge feature
Output
Terminal window
Auto-merging file.txt
CONFLICT (content): Merge conflict in file.txt
Automatic merge failed; fix conflicts and then commit the result.
  • Conflict markers indicate conflict regions
  • Edit files to remove markers and pick resolution
  • Stage and commit after resolution

Remote Tracking

Manage remote repositories and tracking branches.

Configure Remotes and Fetch

Set up and work with remote repositories.

Manage remote repositories

Adds, removes, and manages remote repository references.

Code
Terminal window
# List all remotes
git remote
# List with URLs
git remote -v
# Add new remote
git remote add upstream https://github.com/original/repo.git
# Remove remote
git remote remove origin
# Rename remote
git remote rename origin old-origin
# Change remote URL
git remote set-url origin https://github.com/user/repo.git
Execution
Terminal window
git remote -v
Output
Terminal window
origin https://github.com/user/repo.git (fetch)
origin https://github.com/user/repo.git (push)
upstream https://github.com/original/repo.git (fetch)
  • origin is default remote (clone source)
  • upstream common for forked repositories
  • Separate fetch and push URLs possible

Fetch from remotes

Downloads remote branch updates without merging. Safe operation for syncing.

Code
Terminal window
# Fetch from default remote
git fetch
# Fetch from specific remote
git fetch origin
# Fetch from all remotes
git fetch --all
# Fetch specific branch
git fetch origin main
# Prune deleted remote branches
git fetch --prune
# Fetch and fast-forward
git fetch origin && git merge
Execution
Terminal window
git fetch --all
Output
Terminal window
Fetching origin
remote: Counting objects: 5, done.
Unpacking objects: 100% (3/3), done.
From github.com:user/repo
a1b2c3d..x8y9z0a main -> origin/main
  • Fetch updates remote tracking branches
  • --all fetches from all remotes
  • --prune removes deleted remote branches

Tracking Branch Configuration

Set up and manage upstream tracking relationships.

Set up tracking branches

Establishes connection between local and remote branches for tracking.

Code
Terminal window
# Set upstream for current branch
git branch -u origin/main
# Set upstream when pushing new branch
git push -u origin feature
# Create tracking branch from remote
git checkout --track origin/feature
# Create with specific local name
git checkout -b my-feature origin/feature
# View tracking status
git branch -vv
Execution
Terminal window
git branch -vv
Output
Terminal window
main a1b2c3d [origin/main] Update docs
feature x8y9z0a [origin/feature] Add feature
  • Tracking enables git pull to work without arguments
  • Shows ahead/behind status
  • -vv shows verbose with tracking branch

Update tracking branches

Pulls and integrates remote changes using tracking relationship.

Code
Terminal window
# Pull current branch (requires tracking)
git pull
# Pull specific branch
git pull origin main
# Pull with rebase
git pull --rebase
# See what will be pulled
git fetch && git log --oneline origin/main..main
Execution
Terminal window
git pull --rebase
Output
Terminal window
From github.com:user/repo
a1b2c3d..x8y9z0a main -> origin/main
Fast-forward
  • Tracking branch simplifies pull/push
  • --rebase preferred for linear history

Extras & Tips

Advanced utilities and best practices for Git workflows.

Bisect and Debugging

Find problematic commits using binary search.

Use git bisect

Binary search through commits to find where bug was introduced.

Code
Terminal window
# Start bisect session
git bisect start
# Mark current commit as bad
git bisect bad
# Mark known good commit
git bisect good a1b2c3d
# Test current state and mark
git bisect good # or git bisect bad
# Continue until found
# ... (git will narrow down)
# Reset after finding bad commit
git bisect reset
Execution
Terminal window
git bisect start
Output
Terminal window
Bisecting: 5 revisions left to test after this (roughly 2 steps)
[a1b2c3d] Commit message
  • Efficient Way to find regression
  • Automatically narrows search space
  • Mark commits as good or bad

Find changes with blame

Annotates each line with commit hash, author, and date that changed it.

Code
Terminal window
# Show who changed each line
git blame filename.txt
# Show abbreviated blame
git blame -s filename.txt
# Show blame for specific range
git blame -L 10,20 filename.txt
# Show blame with commit date
git blame --date=short filename.txt
Execution
Terminal window
git blame filename.txt
Output
Terminal window
a1b2c3d (John Doe 2025-01-15 10:30:00 +0000) line content
x8y9z0a (Jane Smith 2025-02-01 14:22:00 +0000) line content
  • Useful for tracking origin of bugs
  • Helps understand code history

Signing and Maintenance

GPG signing commits and repository cleanup.

Sign commits with GPG

Signs commits with GPG key for authentication and verification.

Code
Terminal window
# Configure GPG signing
git config --global user.signingkey YOUR_GPG_KEY_ID
# Sign individual commit
git commit -S -m "Signed commit"
# Sign all commits by default
git config --global commit.gpgSign true
# Verify signed commit
git verify-commit a1b2c3d
# Show GPG signature in log
git log --show-signature
Execution
Terminal window
git commit -S -m "Signed commit"
Output
Terminal window
[main a1b2c3d] Signed commit
1 file changed, 10 insertions(+)
  • Requires GPG key setup
  • -S flag signs commit
  • GitHub shows verification badge for signed commits

Repository maintenance

Performs repository maintenance and cleanup operations.

Code
Terminal window
# Remove empty commits
git gc
# Run full optimization
git gc --aggressive
# Clean untracked files
git clean -fd
# View repo size
git count-objects -v
# Remove large files from history
git filter-branch --tree-filter 'rm -f large-file.bin'
Execution
Terminal window
git gc
Output
Terminal window
Counting objects, done.
  • gc compresses repository (safe)
  • clean removes untracked files
  • filter-branch rewrites history (careful!)

Aliases and Shortcuts

Create custom commands and optimize workflows.

Create command aliases

Creates shorthand commands for frequently used git operations.

Code
Terminal window
# Create short alias
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
# Create complex aliases
git config --global alias.log-graph \
'log --graph --all --oneline --decorate'
# Create unstage alias
git config --global alias.unstage 'restore --staged'
# Create last-commit alias
git config --global alias.last 'log -1 HEAD'
Execution
Terminal window
git config --global alias.st status
  • Aliases stored in ~/.gitconfig
  • Saves time on repetitive commands
  • Can create very complex aliases

Useful workflow aliases

Streamlines common workflows with custom commands.

Code
Terminal window
# Amend without editing message
git config --global alias.amend 'commit --amend --no-edit'
# Pull with rebase
git config --global alias.pr 'pull --rebase'
# List branches by date
git config --global alias.branches \
'branch -a --sort=-committerdate'
# Show recent branches
git config --global alias.recent 'for-each-ref --sort=-committerdate'
Execution
Terminal window
git amend
Output
Terminal window
[main a1b2c3d] Commit message
  • Create aliases for operations you use frequently
  • Improves productivity and reduces errors