The Definitive Guide to Every Git & GitHub Command
2026 Edition
The Complete Git & GitHub Command Reference
Every command you’ll ever need — from your first commit to managing enterprise-scale repositories. Organized by workflow, explained with real examples.
Before writing a single line of code, configure Git with your identity and preferences. These settings live globally on your machine or locally per repository.
git configEssential
Set your identity, editor, default branch name, and other preferences. Global settings apply to all repos; local settings override per-project.
# Set your identity (required before any commit)
git config –global user.name “Jane Doe”
git config –global user.email “jane@example.com”# Set default editor and branch name
git config –global core.editor “code –wait”
git config –global init.defaultBranch “main”# Enable colored output
git config –global color.ui auto# View all current settings
git config –list# Set config for this repo only
git config –local user.email “jane@work.com”
git config –global aliasIntermediate
Create shortcuts for commands you use frequently. Aliases save keystrokes and can encode complex workflows into a single word.
Every Git journey starts here — either by initializing a new project or cloning an existing one.
git initEssential
Create a brand-new Git repository in the current directory. This creates a hidden .git folder that tracks all changes.
# Initialize in the current folder
git init# Initialize with a specific branch name
git init -b main# Create a bare repo (for servers, no working directory)
git init –bare project.git
git cloneEssential
Download a complete copy of a remote repository, including all history, branches, and tags.
# Clone via HTTPS
git clone https://github.com/user/repo.git# Clone via SSH
git clone git@github.com:user/repo.git# Clone into a specific folder
git clone https://github.com/user/repo.git my-folder# Shallow clone (only latest commit — great for large repos)
git clone –depth 1 https://github.com/user/repo.git# Clone a specific branch
git clone -b develop https://github.com/user/repo.git
📦
Staging & Committing
The core loop of Git: check what changed, stage the files you want, and commit a snapshot. Mastering this trio is 80% of everyday Git.
git statusEssential
View which files are modified, staged, or untracked. Your go-to command for situational awareness.
git status# Compact one-line output
git status -s M README.md (modified, not staged)M index.html (modified, staged)?? newfile.txt (untracked)
git addEssential
Move changes from your working directory into the staging area — the “loading dock” before a commit.
# Stage a specific file
git add index.html# Stage multiple files
git add file1.js file2.js# Stage all changes in current directory
git add .# Stage all changes everywhere
git add -A# Interactive staging — pick individual hunks
git add -p# Stage only tracked (modified/deleted) files
git add -u
git commitEssential
Save a snapshot of all staged changes with a descriptive message. Every commit is a checkpoint you can return to.
# Commit with a message
git commit -m“Add user authentication module”# Stage all tracked changes AND commit in one step
git commit -am“Fix login validation bug”# Open editor for a longer commit message
git commit# Amend the previous commit (change message or add files)
git add forgotten-file.js
git commit –amend-m“Updated commit message”# Create an empty commit (useful for triggering CI)
git commit –allow-empty-m“Trigger rebuild”
git diffEssential
See exactly what changed, line by line. Compare working directory, staging area, or any two commits.
# Changes not yet staged
git diff# Changes that are staged (ready to commit)
git diff –staged# Diff between two branches
git diff main..feature-branch# Diff a specific file
git diff — path/to/file.js# Show only names of changed files
git diff –name-only# Word-level diff (great for prose)
git diff –word-diff
git rmIntermediate
Remove files from both the working directory and staging area. Use --cached to stop tracking a file without deleting it.
# Remove a file from repo and disk
git rm old-file.js# Stop tracking but keep the file on disk
git rm –cached secrets.env# Remove a directory recursively
git rm -r old-folder/
git mvIntermediate
Rename or move a file while preserving Git’s tracking history.
Branches let you develop features, fix bugs, and experiment in isolation. They’re lightweight and fast — use them liberally.
git branchEssential
List, create, rename, or delete branches.
# List local branches (* = current)
git branch
* main feature/auth fix/header-bug# List all branches (local + remote)
git branch -a# Create a new branch
git branch feature/search# Rename current branch
git branch -m new-branch-name# Delete a merged branch
git branch -d old-branch# Force-delete an unmerged branch
git branch -D experimental-branch# See which branches are merged into main
git branch –merged main
git checkoutEssential
Switch between branches or restore files to a previous state. The classic multi-purpose command.
# Switch to an existing branch
git checkout develop# Create AND switch to a new branch
git checkout -b feature/dashboard# Restore a file to its last committed state
git checkout — file.js# Check out a specific commit (detached HEAD)
git checkout abc1234
git switchEssential
The modern, cleaner replacement for git checkout when you just want to change branches.
# Switch to an existing branch
git switch develop# Create and switch to a new branch
git switch -c feature/notifications# Switch back to the previous branch
git switch –
git restoreEssential
The modern replacement for git checkout when you want to restore files (not switch branches).
# Discard changes in working directory
git restore file.js# Unstage a file (move out of staging area)
git restore –staged file.js# Restore file to a specific commit’s version
git restore –source abc1234 file.js
🔀
Merging & Rebasing
Integrate work from different branches. Merge preserves history as-is; rebase rewrites it for a cleaner linear timeline.
git mergeEssential
Combine another branch’s changes into your current branch. Creates a merge commit that ties both histories together.
# Merge feature branch into main
git switch main
git merge feature/auth# Merge without fast-forward (always create merge commit)
git merge –no-ff feature/auth# Abort a conflicted merge
git merge –abort# Squash all commits into one before merging
git merge –squash feature/auth
git commit -m“Add auth feature”
git rebaseAdvanced
Replay your branch’s commits on top of another branch, creating a clean linear history. Powerful but rewrites commit hashes.
# Rebase current branch onto main
git rebase main# Interactive rebase — squash, reorder, edit commits
git rebase -i HEAD~5# Continue after resolving conflicts
git rebase –continue# Abort the rebase entirely
git rebase –abort# Rebase onto a specific commit
git rebase –onto main feature-a feature-b
⚠️ Golden Rule of Rebasing
Never rebase commits that have already been pushed to a shared branch. Rewriting shared history creates chaos for your teammates. Rebase your own local work before pushing — not after.
git cherry-pickAdvanced
Apply a specific commit from another branch onto your current branch without merging everything.
# Apply a single commit
git cherry-pick abc1234# Apply multiple commits
git cherry-pick abc1234 def5678# Cherry-pick without auto-committing
git cherry-pick –no-commit abc1234
🌐
Remote Repositories
Connect your local repo to GitHub, GitLab, or any remote server. Push your work up, pull others’ changes down.
git remoteEssential
Manage connections to remote repositories. origin is the conventional name for your primary remote.
# List remotes
git remote -v# Add a remote
git remote add origin https://github.com/user/repo.git# Add a second remote (e.g., for a fork)
git remote add upstream https://github.com/original/repo.git# Change a remote’s URL
git remote set-url origin git@github.com:user/repo.git# Remove a remote
git remote remove old-remote# Rename a remote
git remote rename origin primary
git pushEssential
Upload your local commits to a remote repository.
# Push current branch
git push# Push and set upstream tracking
git push -u origin feature/dashboard# Push all branches
git push –all# Push tags
git push –tags# Force push (rewrites remote history — use carefully!)
git push –force-with-lease# Delete a remote branch
git push origin –delete old-branch
git pullEssential
Download remote changes and immediately merge them into your current branch. Equivalent to fetch + merge.
# Pull from tracked upstream
git pull# Pull from a specific remote/branch
git pull origin main# Pull with rebase instead of merge (cleaner history)
git pull –rebase# Set rebase as default pull strategy
git config –global pull.rebase true
git fetchEssential
Download remote changes without merging. A safer “look before you leap” approach compared to pull.
# Fetch from default remote
git fetch# Fetch from all remotes
git fetch –all# Fetch and prune deleted remote branches
git fetch –prune# Then inspect what changed before merging
git log main..origin/main –oneline
🔍
Inspection & History
Explore your project’s history, find who changed what, and understand how code evolved over time.
git logEssential
View the commit history with powerful formatting and filtering options.
# Standard log
git log# Compact one-line format
git log –oneline# Visual branch graph
git log –oneline–graph–all# Filter by author
git log –author=“Jane”# Filter by date range
git log –after=“2025-01-01”–before=“2025-06-01”# Filter by commit message content
git log –grep=“fix”# Show changes for a specific file
git log -p— path/to/file.js# Show last 5 commits
git log -5# Custom pretty format
git log –pretty=format:“%h %an %ar – %s”
git showIntermediate
Display detailed information about a commit, tag, or any Git object.
# Show the latest commit’s details and diff
git show# Show a specific commit
git show abc1234# Show a file at a specific commit
git show abc1234:path/to/file.js# Show only the commit message (no diff)
git show –stat abc1234
git blameIntermediate
See who last modified each line of a file and when. Indispensable for understanding code ownership.
# Blame a whole file
git blame index.js# Blame specific line range
git blame -L 10,25 index.js# Ignore whitespace changes
git blame -w index.js# Show email instead of name
git blame -e index.js
git shortlogIntermediate
Summarize commit history grouped by author. Great for release notes and contribution stats.
# Summary by author with commit count
git shortlog -sn 142 Jane Doe 87 John Smith 34 Alex Chen# Filter by date
git shortlog -sn–after=“2025-01-01”
git reflogAdvanced
Your safety net — view a log of every position HEAD has been at. Recover “lost” commits, undo bad rebases, and restore deleted branches.
# Show the reflog
git reflog
abc1234 HEAD@{0}: commit: Add new featuredef5678 HEAD@{1}: checkout: moving from main to featureghi9012 HEAD@{2}: reset: moving to HEAD~1# Recover a “lost” commit
git checkout abc1234
git switch -c recovered-branch
💡 Pro Tipgit reflog is your “undo” button for almost anything. Accidentally deleted a branch? Force-pushed the wrong thing? The reflog has your back — commits stay in it for ~90 days by default.
git bisectAdvanced
Use binary search to find the exact commit that introduced a bug. Halves your search space with each step.
# Start bisecting
git bisect start# Mark current version as bad
git bisect bad# Mark a known good commit
git bisect good v2.0.0# Git checks out a middle commit — test it, then:
git bisect good # if this commit works
git bisect bad # if this commit is broken# Repeat until Git finds the culprit, then:
git bisect reset
⏪
Undoing Changes
Everyone makes mistakes. Git gives you multiple levels of “undo” — from discarding edits to rewriting history.
git resetAdvanced
Move the current branch pointer backward. Three modes control what happens to your changes.
# Soft: undo commit, keep changes staged
git reset –soft HEAD~1# Mixed (default): undo commit, unstage changes
git reset HEAD~1# Hard: undo commit AND discard all changes ⚠️
git reset –hard HEAD~1# Reset to a specific commit
git reset –hard abc1234# Unstage a file (without changing file contents)
git reset HEAD file.js
git revertEssential
Create a new commit that undoes a previous commit’s changes. Safe for shared branches because it doesn’t rewrite history.
# Revert the most recent commit
git revert HEAD# Revert a specific commit
git revert abc1234# Revert without auto-committing
git revert –no-commit abc1234# Revert a merge commit
git revert -m 1 abc1234
git cleanDangerous
Remove untracked files from the working directory. Irreversible — always preview with -n first.
# Preview what would be removed (dry run)
git clean -n# Remove untracked files
git clean -f# Remove untracked files AND directories
git clean -fd# Also remove ignored files
git clean -fdx
📋
Stashing
Need to switch branches but have uncommitted work? Stash saves your changes temporarily so you can come back to them later.
git stashEssential
Temporarily shelve modified tracked files so you can work on something else, then restore them later.
# Stash current changes
git stash# Stash with a descriptive message
git stash push -m“WIP: refactoring navbar”# Include untracked files
git stash -u# List all stashes
git stash list
stash@{0}: WIP: refactoring navbarstash@{1}: WIP on main: abc1234 fix typo# Apply most recent stash (keeps it in list)
git stash apply# Apply and remove from list
git stash pop# Apply a specific stash
git stash apply stash@{2}# View stash contents
git stash show -p stash@{0}# Create a branch from a stash
git stash branch new-branch stash@{0}# Drop a specific stash
git stash drop stash@{1}# Clear all stashes
git stash clear
🏷️
Tagging & Releases
Tags mark specific points in history — typically releases. They’re like bookmarks that never move.
git tagIntermediate
Create, list, and manage tags. Annotated tags store extra metadata; lightweight tags are just pointers.
# Create an annotated tag (recommended)
git tag -a v1.0.0 -m“First stable release”# Create a lightweight tag
git tag v1.0.0-beta# Tag a specific past commit
git tag -a v0.9.0 -m“Beta release” abc1234# List all tags
git tag# List tags matching a pattern
git tag -l“v1.*”# Show tag details
git show v1.0.0# Push a tag to remote
git push origin v1.0.0# Push all tags
git push –tags# Delete a local tag
git tag -d v1.0.0# Delete a remote tag
git push origin –delete v1.0.0
🧬
Advanced Git
Power-user commands for managing submodules, optimizing repos, debugging, and automating workflows.
git submoduleAdvanced
Embed one Git repository inside another. Useful for shared libraries or dependencies you want to pin to a specific version.
# Add a submodule
git submodule add https://github.com/lib/utils.git libs/utils# Initialize submodules after cloning
git submodule init
git submodule update# Clone a repo with all submodules
git clone –recurse-submodules https://github.com/user/repo.git# Update all submodules to latest
git submodule update –remote# Remove a submodule
git submodule deinit libs/utils
git rm libs/utils
git worktreeAdvanced
Check out multiple branches simultaneously in different directories. Work on a hotfix without stashing your feature work.
# Create a new worktree for a branch
git worktree add ../hotfix-dir hotfix/urgent-fix# List all worktrees
git worktree list# Remove a worktree
git worktree remove ../hotfix-dir
git grepIntermediate
Search through tracked files for a pattern. Faster than regular grep because it only searches Git-tracked content.
# Search for a string
git grep “TODO”# Search with line numbers
git grep -n“console.log”# Search in a specific commit
git grep “deprecated” v2.0.0# Count occurrences per file
git grep -c“import”
git archiveIntermediate
Create a zip or tar archive of your project (without the .git directory). Perfect for distributing source code.
# Create a zip of the current HEAD
git archive –format=zip–output=release.zip HEAD# Create a tarball of a specific tag
git archive –format=tar.gz–prefix=myapp-1.0/ v1.0.0 > release.tar.gz
# Run garbage collection
git gc# Aggressive optimization (slower but more thorough)
git gc –aggressive# Prune old objects
git gc –prune=now
git filter-branch / git filter-repoDangerous
Rewrite repository history to remove sensitive files, change author info, or restructure the project. Prefer git filter-repo (a separate tool) over the older filter-branch.
# Remove a sensitive file from all history (using filter-repo)
git filter-repo –path secrets.env –invert-paths# Change author email across all commits
git filter-repo –email-callback‘
return email.replace(b”old@email.com”, b”new@email.com”)
‘
git hooksAdvanced
Scripts that run automatically at key Git events — before commits, pushes, merges, etc. Stored in .git/hooks/.
# Common hooks (create as executable scripts in .git/hooks/):# pre-commit → Run linters, tests before commit# commit-msg → Validate commit message format# pre-push → Run test suite before pushing# post-merge → Auto-install dependencies after merge# Example pre-commit hook (.git/hooks/pre-commit):
#!/bin/sh
npm run lint || exit 1
npm test || exit 1
.gitignoreEssential
Tell Git which files and directories to ignore. Essential for keeping build artifacts, dependencies, and secrets out of your repo.
# Common .gitignore patterns:
node_modules/
dist/
build/
*.env
*.log
.DS_Store
__pycache__/
*.pyc
.vscode/
coverage/# Force-add an ignored file (override)
git add -f important.env# Check why a file is ignored
git check-ignore -v myfile.log
🐙
GitHub CLI (gh)
The official GitHub command-line tool. Manage pull requests, issues, repos, workflows, and more without leaving the terminal. Install it at cli.github.com.
gh authEssential
Authenticate with your GitHub account.
# Interactive login
gh auth login# Check auth status
gh auth status# Login with a token
gh auth login –with-token < token.txt# Logout
gh auth logout
gh repoEssential
Create, clone, fork, and manage repositories from the terminal.
# Create a new repo
gh repo create my-project –public# Create from current directory
gh repo create –source=.–public–push# Clone a repo
gh repo clone user/repo# Fork a repo
gh repo fork user/repo –clone# View repo in browser
gh repo view –web# List your repos
gh repo list# Archive a repo
gh repo archive my-old-project
gh prEssential
Create, review, merge, and manage pull requests entirely from the command line.
# Create a pull request
gh pr create –title“Add dark mode”–body“Implements #42”# Create PR interactively
gh pr create# List open PRs
gh pr list# View PR details
gh pr view 123# Check out a PR locally
gh pr checkout 123# Review a PR
gh pr review 123 –approve
gh pr review 123 –request-changes–body“Needs tests”# Merge a PR
gh pr merge 123 –squash–delete-branch# View PR diff
gh pr diff 123# Check PR CI status
gh pr checks 123
gh issueEssential
Create, list, and manage GitHub issues without opening a browser.
# Create an issue
gh issue create –title“Bug: login fails”–body“Steps to reproduce…”# Create with labels and assignee
gh issue create –title“Add export feature”–label“enhancement”–assignee“@me”# List open issues
gh issue list# Filter by label
gh issue list –label“bug”# View issue details
gh issue view 42# Close an issue
gh issue close 42# Reopen an issue
gh issue reopen 42
gh workflow / gh runIntermediate
View, trigger, and manage GitHub Actions workflows and their runs.
# List workflows
gh workflow list# Trigger a workflow manually
gh workflow run deploy.yml# View recent runs
gh run list# Watch a run in real-time
gh run watch# View run logs
gh run view 12345 –log# Re-run a failed workflow
gh run rerun 12345 –failed
gh gistIntermediate
Create and manage GitHub Gists — shareable code snippets.
# Create a gist from a file
gh gist create script.py# Create a public gist with description
gh gist create –public-d“Handy utility” utils.js# List your gists
gh gist list# View a gist
gh gist view abc123# Edit a gist
gh gist edit abc123
Manage encrypted secrets for GitHub Actions directly from the CLI.
# Set a secret
gh secret set API_KEY# Set from a file
gh secret set DB_PASSWORD < db-password.txt# List secrets
gh secret list# Delete a secret
gh secret delete API_KEY# Set an environment-specific secret
gh secret set API_KEY –env production
gh apiAdvanced
Make raw GitHub API requests directly. Access any endpoint for advanced automation.
# Get your profile
gh api user# List repo contributors
gh api repos/user/repo/contributors# Create a label
gh api repos/user/repo/labels -f name=“priority:high”-f color=“FF0000”# Paginate through results
gh api repos/user/repo/issues –paginate
gh codespaceIntermediate
Create and manage GitHub Codespaces — cloud-hosted development environments.
# Create a codespace for a repo
gh codespace create -r user/repo# List your codespaces
gh codespace list# Open in VS Code
gh codespace code# SSH into a codespace
gh codespace ssh# Stop a codespace
gh codespace stop# Delete a codespace
gh codespace delete
Comments are closed.