Git Commands Cheat Sheet: From Beginner to Advanced

Git is the version control system that runs the modern software world. Whether you are making your first commit or resolving a hairy rebase conflict, the commands in this cheat sheet cover every scenario you will encounter. Bookmark this page and come back to it every time you need a command you cannot quite remember.

Setup and Configuration

Configure your identity before your first commit. These settings are stored in ~/.gitconfig.

# Set your name and email (required for commits)
git config --global user.name "Your Name"
git config --global user.email "you@example.com"

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

# Set default editor
git config --global core.editor "code --wait"    # VS Code
git config --global core.editor "vim"             # Vim

# Enable colored output
git config --global color.ui auto

# View all configuration
git config --list
git config --global --list

# Set credential caching (avoid re-entering password)
git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=3600'

Initialize or clone a repository:

# Create a new repository in the current directory
git init

# Create a new repository in a specific directory
git init my-project

# Clone a remote repository
git clone https://github.com/user/repo.git

# Clone into a specific folder
git clone https://github.com/user/repo.git my-folder

# Clone a specific branch
git clone -b develop https://github.com/user/repo.git

# Shallow clone (only recent history — faster for large repos)
git clone --depth 1 https://github.com/user/repo.git

Basic Workflow

The core loop you will use hundreds of times a day: check status, stage changes, commit.

# Check the state of your working directory
git status
git status -s          # short format

# Stage files for commit
git add file.txt               # stage a specific file
git add src/                   # stage an entire directory
git add *.py                   # stage all Python files
git add -A                     # stage everything (new, modified, deleted)
git add -p                     # interactively stage hunks within files

# Commit staged changes
git commit -m "Add user login feature"

# Commit with a multi-line message
git commit -m "Add user login feature" -m "Implements OAuth2 flow with Google and GitHub providers."

# Stage all tracked modified files and commit in one step
git commit -am "Fix typo in header"

# View differences
git diff                   # unstaged changes vs last commit
git diff --staged          # staged changes vs last commit
git diff HEAD              # all changes (staged + unstaged) vs last commit
git diff branch1 branch2   # differences between two branches
git diff abc123 def456     # differences between two commits

Branching

Branches let you work on features, fixes, and experiments in isolation.

# List branches
git branch             # local branches
git branch -r          # remote branches
git branch -a          # all branches (local + remote)
git branch -v          # branches with last commit info

# Create a new branch
git branch feature-login

# Create and switch to a new branch
git checkout -b feature-login
git switch -c feature-login      # modern alternative (Git 2.23+)

# Switch branches
git checkout main
git switch main                  # modern alternative

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

# Delete a branch
git branch -d feature-login      # safe delete (only if merged)
git branch -D feature-login      # force delete (even if unmerged)

# Delete a remote branch
git push origin --delete feature-login

Merging

# Merge a branch into the current branch
git merge feature-login

# Merge with a commit message (no fast-forward)
git merge --no-ff feature-login -m "Merge feature-login into main"

# Abort a merge in progress (if there are conflicts)
git merge --abort

# View merge conflicts
git diff --name-only --diff-filter=U

When you hit a merge conflict, Git marks the conflicting sections in the file:

<<<<<<< HEAD
your changes
=======
their changes
>>>>>>> feature-login

Edit the file to resolve the conflict, then:

git add resolved-file.txt
git commit

Working with Remotes

# View remotes
git remote -v

# Add a remote
git remote add origin https://github.com/user/repo.git
git remote add upstream https://github.com/original/repo.git

# Change a remote URL
git remote set-url origin https://github.com/user/new-repo.git

# Remove a remote
git remote remove upstream

# Fetch changes from remote (does not merge)
git fetch origin
git fetch --all              # fetch from all remotes

# Pull changes (fetch + merge)
git pull origin main
git pull --rebase origin main    # fetch + rebase instead of merge

# Push changes
git push origin main
git push -u origin main          # set upstream tracking (first push)
git push origin feature-login    # push a feature branch
git push --tags                  # push all tags
git push origin --delete branch  # delete a remote branch

# View tracking information
git branch -vv

Viewing History

# View commit log
git log
git log --oneline                    # compact one-line format
git log --oneline --graph            # with branch graph
git log --oneline --graph --all      # all branches
git log -5                           # last 5 commits
git log --author="Alice"             # filter by author
git log --since="2025-01-01"         # commits after a date
git log --until="2025-06-30"         # commits before a date
git log --grep="fix"                 # search commit messages
git log -- path/to/file.py           # history of a specific file
git log -p -- file.py                # history with diffs

# View a specific commit
git show abc1234
git show HEAD                        # latest commit
git show HEAD~2                      # two commits ago

# Who changed each line of a file
git blame file.py
git blame -L 10,20 file.py          # lines 10-20 only

# View the reflog (every HEAD movement — your safety net)
git reflog
git reflog show feature-login        # reflog for a specific branch

The reflog is your emergency recovery tool. Even after a bad reset or deleted branch, the reflog retains references for at least 30 days.

Undoing Changes

This is the section you will come back to most often. Git provides several ways to undo work, each with different implications.

# Discard unstaged changes in a file (restore to last commit)
git restore file.py
git checkout -- file.py              # older syntax, same effect

# Unstage a file (keep changes in working directory)
git restore --staged file.py
git reset HEAD file.py               # older syntax

# Undo the last commit but keep changes staged
git reset --soft HEAD~1

# Undo the last commit and unstage changes (keep in working directory)
git reset --mixed HEAD~1             # --mixed is the default
git reset HEAD~1

# Undo the last commit and discard all changes entirely
git reset --hard HEAD~1

# Create a new commit that reverses a previous commit (safe for shared branches)
git revert abc1234
git revert HEAD                      # revert the latest commit

# Restore a specific file from a specific commit
git restore --source=abc1234 -- file.py
git checkout abc1234 -- file.py      # older syntax

When to use reset vs. revert: - Use git reset when you are rewriting history on a branch that only you use. - Use git revert when you need to undo a commit on a shared branch. It creates a new commit, so it does not rewrite history.

Stashing

Stash lets you save uncommitted changes temporarily so you can switch branches or pull updates.

# Stash current changes
git stash
git stash -m "work in progress on login page"

# Stash including untracked files
git stash -u

# Stash including untracked and ignored files
git stash -a

# List all stashes
git stash list

# Apply the most recent stash (keeps it in stash list)
git stash apply

# Apply and remove the most recent stash
git stash pop

# Apply a specific stash
git stash apply stash@{2}

# View the contents of a stash
git stash show stash@{0}
git stash show -p stash@{0}         # with full diff

# Drop a specific stash
git stash drop stash@{1}

# Clear all stashes
git stash clear

# Create a branch from a stash
git stash branch new-branch stash@{0}

Advanced Operations

Rebase

Rebase replays your commits on top of another branch, creating a linear history.

# Rebase current branch onto main
git rebase main

# Abort a rebase in progress
git rebase --abort

# Continue after resolving conflicts
git rebase --continue

# Skip a conflicting commit
git rebase --skip

Cherry-Pick

Apply a specific commit from another branch to your current branch.

git cherry-pick abc1234
git cherry-pick abc1234 def5678      # multiple commits
git cherry-pick abc1234 --no-commit  # apply changes without committing

Bisect

Binary search through history to find which commit introduced a bug.

git bisect start
git bisect bad                 # current commit is bad
git bisect good abc1234        # this older commit was good
# Git checks out a middle commit — test it, then:
git bisect good                # or git bisect bad
# Repeat until Git identifies the first bad commit
git bisect reset               # return to original state

Tags

Tags mark specific points in history, typically used for releases.

# Create a lightweight tag
git tag v1.0.0

# Create an annotated tag (recommended for releases)
git tag -a v1.0.0 -m "Release version 1.0.0"

# Tag a specific commit
git tag -a v0.9.0 abc1234 -m "Beta release"

# List tags
git tag
git tag -l "v1.*"              # filter with pattern

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

# Delete a tag
git tag -d v1.0.0              # delete locally
git push origin --delete v1.0.0  # delete from remote

# Checkout a tag
git checkout v1.0.0            # detached HEAD state

.gitignore

The .gitignore file tells Git which files to ignore. Place it in the repository root.

# Compiled files
*.pyc
*.class
*.o

# Directories
node_modules/
__pycache__/
.venv/
dist/
build/

# Environment and secrets
.env
.env.local
*.pem
credentials.json

# OS files
.DS_Store
Thumbs.db

# IDE files
.vscode/
.idea/
*.swp

# Logs
*.log
logs/
# Stop tracking a file that is already tracked (but keep it locally)
git rm --cached file.txt
git rm --cached -r directory/

# Check what is being ignored
git status --ignored

Tips and Useful Aliases

Set up aliases to save keystrokes on commands you use constantly:

git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.lg "log --oneline --graph --all"
git config --global alias.last "log -1 HEAD"
git config --global alias.unstage "restore --staged"

Other useful techniques:

# See which branches contain a specific commit
git branch --contains abc1234

# Find a commit by message text
git log --all --grep="login bug"

# Count commits by author
git shortlog -sn

# Show file at a specific commit without checking it out
git show abc1234:path/to/file.py

# Clean up untracked files (dry run first)
git clean -n             # show what would be deleted
git clean -f             # actually delete
git clean -fd            # delete files and directories

# Compress repository (run periodically for performance)
git gc

# List all files tracked by Git
git ls-files

Quick Reference

Task Command
Initialize repo git init
Clone repo git clone <url>
Check status git status
Stage file git add <file>
Commit git commit -m "message"
Create branch git switch -c <name>
Switch branch git switch <name>
Merge branch git merge <branch>
Pull latest git pull
Push changes git push
View log git log --oneline
Undo last commit (keep changes) git reset --soft HEAD~1
Revert a commit (safe) git revert <hash>
Stash changes git stash
Apply stash git stash pop
View diff git diff
Tag a release git tag -a v1.0 -m "msg"

This cheat sheet covers everything from your first commit to advanced operations like bisect and cherry-pick. Keep it bookmarked, and you will never be stuck wondering how to undo a commit or resolve a merge conflict again.

Learn to build software with AI in our free Vibe Coding textbook.