Complete Reference · Free Download

Git & GitHub
Cheat Sheet

Every essential Git command and GitHub workflow in one place — init, staging, branching, merging, remotes, rebase, stash, GitHub Actions, and more.

Browse Cheat Sheet ↓
16+Topics Covered
200+Commands
8 pagesPDF Download
FreeAlways
Getting Started

Git Setup & Config

Configure your Git identity, editor preferences, and initialize repositories before you start tracking code.

⚙️
Global Configuration
Set your identity and preferences globally or per-repo.
bash
# Set your identity (required for commits)
git config --global user.name "Your Name"
git config --global user.email "you@example.com"

# Set default editor
git config --global core.editor code    # VS Code
git config --global core.editor nano    # nano

# Set default branch name
git config --global init.defaultBranch main

# View all config
git config --list

# Set line ending handling
git config --global core.autocrlf input  # macOS/Linux
git config --global core.autocrlf true   # Windows

# Enable color output
git config --global color.ui auto
🚀
Initialize & Clone
Start a new repo or clone an existing one.
bash
# Initialize a new repository
git init
git init my-project     # in new folder

# Clone a repository
git clone <url>
git clone <url> folder-name   # rename

# Clone specific branch
git clone -b main <url>

# Clone with depth (shallow)
git clone --depth 1 <url>

# Clone via SSH
git clone git@github.com:user/repo.git

# Show repo info
git remote -v
Core Workflow

Staging, Committing & Status

The daily Git workflow — checking status, staging files, and creating commits that tell the story of your project.

📋
Status & Inspection
Check what's changed and what's staged.
bash
# Check working tree status
git status
git status -s          # short format

# Show unstaged changes
git diff

# Show staged changes
git diff --staged

# Show diff of specific file
git diff file.txt

# Show diff between branches
git diff main..feature

# Show commit summary
git show HEAD
git show abc1234     # specific commit
Staging Files
Add files to the staging area before committing.
bash
# Stage a specific file
git add file.txt

# Stage all changes
git add .
git add -A            # all incl. deletions

# Stage interactively (patch)
git add -p

# Unstage a file
git restore --staged file.txt

# Remove from tracking
git rm file.txt
git rm --cached file.txt  # keep file

# Move / rename
git mv old.txt new.txt
💾
Committing
Save your staged snapshot to the project history.
bash
# Commit staged changes
git commit -m "feat: add login page"

# Stage + commit tracked files
git commit -am "fix: typo"

# Amend last commit
git commit --amend
git commit --amend -m "new message"
git commit --amend --no-edit  # same msg

# Empty commit (trigger CI)
git commit --allow-empty -m "trigger"

# Conventional commits
# feat: | fix: | docs: | chore:
# refactor: | test: | style:

📄 .gitignore Patterns

Pattern Matches Example
*.log All .log files error.log
build/ build directory build/index.js
!important.log Negate (don't ignore) important.log
doc/**/*.txt All .txt inside doc/ doc/a/b.txt
[Dd]ebug Debug or debug folder Debug/
.env* All .env files .env.local
Version Control

Branching

Create, switch, and manage branches — the backbone of parallel development and feature isolation.

🌿
Branch Operations
Create, list, rename, and delete branches.
bash
# List all branches
git branch
git branch -a           # incl. remote
git branch -v           # with last commit

# Create a new branch
git branch feature/login

# Create and switch immediately
git checkout -b feature/login
git switch -c feature/login  # modern

# Rename a branch
git branch -m old-name new-name

# Delete a branch
git branch -d feature/login  # safe
git branch -D feature/login  # force

# List merged/unmerged branches
git branch --merged
git branch --no-merged
🔄
Switching Branches
Navigate between branches and detached HEAD states.
bash
# Switch branch (classic)
git checkout main

# Switch branch (modern, Git 2.23+)
git switch main
git switch -           # previous branch

# Checkout at specific commit
git checkout abc1234    # detached HEAD

# Create branch from commit
git checkout -b fix/bug abc1234

# Restore a file to HEAD version
git restore file.txt
git checkout -- file.txt   # old syntax

# Track remote branch
git checkout --track origin/feature
Collaboration

Remote Repositories

Push your work, pull teammates' changes, and manage connections to remote repositories like GitHub.

🌐
Manage Remotes
Add, view, rename and remove remote connections.
bash
# List remotes
git remote
git remote -v           # with URLs

# Add a remote
git remote add origin <url>

# Change remote URL
git remote set-url origin <new-url>

# Rename a remote
git remote rename origin upstream

# Remove a remote
git remote remove origin

# Show remote details
git remote show origin
⬆️
Push Changes
Send local commits to the remote repository.
bash
# Push to remote
git push
git push origin main

# Set upstream and push
git push -u origin main

# Push all branches
git push --all

# Force push (use with caution)
git push --force
git push --force-with-lease  # safer

# Delete remote branch
git push origin --delete feature/x

# Push tags
git push --tags
⬇️
Fetch & Pull
Download remote changes into your local repo.
bash
# Fetch (download, don't merge)
git fetch
git fetch origin
git fetch --all         # all remotes
git fetch --prune       # clean deleted

# Pull (fetch + merge)
git pull
git pull origin main

# Pull with rebase instead of merge
git pull --rebase

# Pull specific remote branch
git pull origin feature/x

# Pull and fast-forward only
git pull --ff-only
Integration

Merging & Rebasing

Combine work from different branches using merge or rebase — and resolve conflicts when they occur.

🔀
Merge
Integrate branches, preserving full history.
bash
# Merge branch into current
git merge feature/login

# Fast-forward only merge
git merge --ff-only feature

# No fast-forward (always create merge commit)
git merge --no-ff feature

# Squash all commits to one
git merge --squash feature

# Abort a merge
git merge --abort

# After fixing conflicts
git add .
git merge --continue
🔁
Rebase
Rewrite history for a clean, linear timeline.
bash
# Rebase current branch onto main
git rebase main

# Interactive rebase (last 3 commits)
git rebase -i HEAD~3

# Interactive options:
# pick   - use commit as-is
# reword - edit commit message
# squash - combine with previous
# drop   - remove commit
# fixup  - squash, discard message

# Abort rebase
git rebase --abort

# Continue after conflict fix
git rebase --continue

# Skip a problematic commit
git rebase --skip
⚠️
Conflict Resolution
Understand and resolve merge conflicts confidently.
bash
# Show conflicted files
git status
git diff --diff-filter=U

# Conflict markers in file:
<<<<<<< HEAD
your changes
=======
incoming changes
>>>>>>> feature/branch

# Accept ours or theirs (whole file)
git checkout --ours   file.txt
git checkout --theirs file.txt

# Use merge tool
git mergetool

# After resolving: add + commit
git add . && git commit
Workflow

Stash & Cherry-pick

Temporarily shelve uncommitted changes or apply specific commits from other branches.

📦
Stash Commands
Save and restore work-in-progress without committing.
bash
# Stash uncommitted changes
git stash
git stash push -m "WIP: login form"

# Stash including untracked
git stash -u
git stash --all       # incl. ignored

# List stashes
git stash list

# Apply latest stash
git stash pop          # apply + delete
git stash apply        # apply, keep stash

# Apply specific stash
git stash pop stash@{2}

# Delete a stash
git stash drop stash@{0}
git stash clear        # delete all

# Create branch from stash
git stash branch fix/stashed-work
🍒
Cherry-pick
Apply specific commits to the current branch.
bash
# Apply a single commit
git cherry-pick abc1234

# Apply range of commits
git cherry-pick abc1234..def5678

# Cherry-pick without committing
git cherry-pick -n abc1234

# Edit commit message
git cherry-pick -e abc1234

# Abort cherry-pick
git cherry-pick --abort

# Continue after conflict fix
git cherry-pick --continue

# Cherry-pick from another remote
git fetch upstream
git cherry-pick upstream/main~1
Inspection

Log & History

Navigate and inspect commit history, understand who changed what, and trace bugs back to their origin.

📜
Git Log
View and format commit history with powerful filters.
bash
# Basic log
git log
git log --oneline           # compact
git log --oneline --graph   # visual

# Last N commits
git log -5

# Filter by author / date
git log --author="Jane"
git log --since="2 weeks ago"
git log --until="2024-01-01"

# Filter by message
git log --grep="login"

# Custom format
git log --pretty=format:"%h %an %s"

# Show files changed per commit
git log --stat
git log -p                  # with diffs
🔍
Blame, Bisect & Grep
Find who changed a line and debug with binary search.
bash
# Show who changed each line
git blame file.txt
git blame -L 10,20 file.txt  # lines 10–20

# Binary search for bug
git bisect start
git bisect bad           # current is broken
git bisect good v1.0    # known good tag
# Git checks out midpoint
git bisect good/bad     # repeat
git bisect reset        # done

# Search across commit history
git log -S "functionName"     # pickaxe
git grep "pattern"            # in files
git grep "pattern" v1.0      # at tag
Recovery

Undoing Changes

Undo mistakes safely with reset, revert, and restore — know when to use each to avoid data loss.

↩️
Git Reset
Move HEAD backwards — use carefully on shared history.
bash
# Soft: keep changes staged
git reset --soft HEAD~1

# Mixed (default): unstage changes
git reset HEAD~1
git reset --mixed HEAD~2

# Hard: discard all changes ⚠️
git reset --hard HEAD~1
git reset --hard origin/main

# Reset to specific commit
git reset --hard abc1234

# Unstage a file
git reset HEAD file.txt
🔄
Git Revert
Safely undo commits by creating new ones — safe for shared branches.
bash
# Revert last commit
git revert HEAD

# Revert specific commit
git revert abc1234

# Revert without auto-commit
git revert -n abc1234

# Revert a range of commits
git revert HEAD~3..HEAD

# Revert a merge commit
git revert -m 1 abc1234

# Abort revert
git revert --abort
🧹
Restore & Clean
Restore files and clean untracked files from the working tree.
bash
# Discard changes in working tree
git restore file.txt
git restore .           # all files

# Restore from specific commit
git restore --source HEAD~2 file.txt

# Remove untracked files
git clean -f            # files
git clean -fd           # files + dirs
git clean -fdi          # interactive

# Dry run (preview)
git clean -n

# Recover a lost commit
git reflog
git checkout -b recover abc1234
Releases

Tags & Releases

Mark significant points in history such as version releases with lightweight or annotated tags.

🏷️
Tag Commands
Create, list, push, and delete version tags.
bash
# List tags
git tag
git tag -l "v1.*"        # filter pattern

# Lightweight tag
git tag v1.0.0

# Annotated tag (recommended)
git tag -a v1.0.0 -m "Release v1.0.0"

# Tag a past commit
git tag -a v0.9 abc1234

# Push a tag
git push origin v1.0.0
git push --tags           # all tags

# Delete local / remote tag
git tag -d v1.0.0
git push origin --delete v1.0.0

# Checkout a tag
git checkout v1.0.0
📊
Semantic Versioning
Standard versioning convention for Git releases.
Type Version Bump When
MAJOR v1.0.0 → v2.0.0 Breaking changes
MINOR v1.0.0 → v1.1.0 New features
PATCH v1.0.0 → v1.0.1 Bug fixes
PRE v2.0.0-alpha.1 Pre-release
  • git describeShow most recent tag + commits ahead
  • --tagsInclude lightweight tags in describe
  • --abbrev=7Shorten commit hash to 7 chars
Platform

GitHub Workflows

Pull requests, forks, issues, and the GitHub collaboration model — the social layer on top of Git.

🐙
Pull Request Flow
The standard PR workflow for contributing code on GitHub.
bash
# 1. Fork repo on GitHub UI
# 2. Clone your fork
git clone git@github.com:you/repo.git

# 3. Add upstream remote
git remote add upstream <original-url>

# 4. Create feature branch
git switch -c feat/my-feature

# 5. Make changes + commit
git add . && git commit -m "feat: ..."

# 6. Push to your fork
git push -u origin feat/my-feature

# 7. Open PR on GitHub
# 8. Sync your fork with upstream
git fetch upstream
git rebase upstream/main
🔑
SSH Keys & Auth
Set up SSH authentication for passwordless GitHub access.
bash
# Generate SSH key
ssh-keygen -t ed25519 -C "you@email.com"

# Copy public key to clipboard
cat ~/.ssh/id_ed25519.pub
# Paste in GitHub Settings → SSH Keys

# Test SSH connection
ssh -T git@github.com

# Start SSH agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

# GitHub CLI authentication
gh auth login
gh auth status

# Create repo via CLI
gh repo create my-project --public
🛠️
GitHub CLI (gh)
Manage GitHub repos, PRs, and issues from the terminal.
bash
# Pull requests
gh pr create            # open new PR
gh pr list
gh pr checkout 42       # checkout PR #42
gh pr merge 42

# Issues
gh issue create
gh issue list
gh issue close 10

# Repos
gh repo clone user/repo
gh repo fork
gh repo view --web      # open in browser

# Releases
gh release create v1.0.0
gh release list
CI/CD

GitHub Actions

Automate your workflows — build, test, and deploy code directly from GitHub using YAML pipeline files.

Workflow Structure
Basic workflow file anatomy and syntax.
yaml
# .github/workflows/ci.yml
name: CI Pipeline

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]
  schedule:
    - cron: '0 6 * * *'   # 6am daily

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm ci
      - run: npm test
🚢
Deploy Workflow
Common deploy-to-production workflow pattern.
yaml
jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4

      # Use secrets
      - env:
          API_KEY: ${{ secrets.API_KEY }}
        run: echo "Deploy with $API_KEY"

      # Cache dependencies
      - uses: actions/cache@v4
        with:
          path: ~/.npm
          key: ${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}

      # Artifacts
      - uses: actions/upload-artifact@v4
        with:
          name: dist-files
          path: dist/

⚡ Actions Keywords Quick Reference

Keyword Description Example
on Event triggers push, pull_request, workflow_dispatch
jobs Parallel/sequential units build, test, deploy
runs-on Runner OS ubuntu-latest, windows-latest, macos-latest
uses Reference an action actions/checkout@v4
run Shell command npm install && npm test
secrets Encrypted vars ${{ secrets.DEPLOY_KEY }}
needs Job dependency needs: [build, test]
if Conditional step if: github.ref == 'refs/heads/main'
Pro Tips

Advanced Git

Submodules, worktrees, aliases, hooks and Git internals — level up your Git mastery.

🔧
Aliases & Config
Speed up daily workflow with custom Git shortcuts.
bash
# Create aliases
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 --decorate"
git config --global alias.undo "reset --soft HEAD~1"
git config --global alias.unstage "restore --staged"

# Use alias
git st       # git status
git lg       # pretty log graph

# Configure merge tool
git config --global merge.tool vscode
git config --global diff.tool vscode
🗂️
Submodules
Embed other Git repositories inside your repo.
bash
# Add a submodule
git submodule add <url> path/to/sub

# Clone repo with submodules
git clone --recurse-submodules <url>

# Initialize after regular clone
git submodule init
git submodule update

# Update all submodules
git submodule update --remote

# Remove a submodule
git submodule deinit path/to/sub
git rm path/to/sub

# Run command in all submodules
git submodule foreach 'git pull'
🪝
Git Hooks
Automate actions at key Git lifecycle points.
bash
# Hooks live in .git/hooks/
# pre-commit: runs before commit
# commit-msg: validate commit message
# pre-push: runs before push
# post-merge: after merge

# Example pre-commit hook:
#!/bin/sh
npm run lint
npm test

# Make executable:
chmod +x .git/hooks/pre-commit

# Use Husky for team hooks:
npx husky init
echo "npm test" > .husky/pre-commit

# Skip hooks (emergency only)
git commit --no-verify

🚀 Power User Quick Reference

  • git worktree addMultiple working trees for same repo
  • git reflogHistory of HEAD movements (safety net)
  • git shortlog -snCommit count per author
  • git archiveExport repo as zip/tar without .git
  • git bundlePack entire repo into single file
  • git gcGarbage collect, compress objects
  • git filter-repoRewrite history (remove files/secrets)
  • git format-patchExport commits as email-ready patches
  • git notesAttach notes to commits
More Resources

Explore More Cheat Sheets

Continue your learning with our other free developer reference guides.

Get Your Free Git & GitHub PDF

Join 50,000+ developers who have downloaded our cheat sheets. Get the PDF in your inbox instantly.

Join WhatsApp Channel