Git is the version control system that powers nearly every software project on Earth. Whether you just installed it for the first time or you've been using it for years, there's always a command you forget, a flag you can never remember, or a mess you need to undo. This guide covers everything — from the absolute basics to advanced workflows — with real examples for every command.
Bookmark this page. You'll come back to it.
Quick Reference: The 30 Commands You'll Use Most
| Command | What It Does |
|---|---|
git init | Initialize a new repository |
git clone <url> | Clone a remote repository locally |
git status | Show the state of the working directory |
git add <file> | Stage a file for the next commit |
git add . | Stage all changes |
git commit -m "message" | Commit staged changes |
git commit -am "message" | Stage tracked files and commit in one step |
git log | View commit history |
git log --oneline | Compact commit history |
git diff | Show unstaged changes |
git diff --staged | Show staged changes |
git branch | List local branches |
git branch <name> | Create a new branch |
git checkout <branch> | Switch to a branch |
git checkout -b <branch> | Create and switch to a new branch |
git switch <branch> | Switch branches (modern syntax) |
git switch -c <branch> | Create and switch (modern syntax) |
git merge <branch> | Merge a branch into the current branch |
git rebase <branch> | Rebase current branch onto another |
git remote -v | List remote connections |
git fetch | Download remote changes without merging |
git pull | Fetch and merge remote changes |
git push | Push local commits to remote |
git push -u origin <branch> | Push and set upstream tracking |
git stash | Temporarily shelve uncommitted changes |
git stash pop | Restore the most recent stash |
git reset HEAD~1 | Undo the last commit, keep changes staged |
git reset --hard HEAD~1 | Undo the last commit, discard changes |
git revert <commit> | Create a new commit that undoes a previous one |
git cherry-pick <commit> | Apply a specific commit to the current branch |
1 Setup and Configuration
Before you write a single line of code, set your identity. Git tags every commit with your name and email.
Setting Your Identity
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
The --global flag applies these settings to all repositories on your machine. To override them for a single project, run the same commands from inside that project's directory without --global.
Checking Your Configuration
git config --list
git config user.name # Check a single value
Setting Your Default Editor
git config --global core.editor "code --wait" # VS Code
git config --global core.editor "vim" # Vim
git config --global core.editor "nano" # Nano
Setting the Default Branch Name
Modern convention uses main instead of master:
git config --global init.defaultBranch main
Viewing the Config File
Git stores global config in ~/.gitconfig. You can open it directly:
git config --global --edit
Useful Configuration Shortcuts
# Always rebase instead of merge on git pull
git config --global pull.rebase true
# Enable colored output
git config --global color.ui auto
# Set a credential helper to avoid re-entering passwords
git config --global credential.helper cache
2 Creating and Cloning Repositories
Initialize a New Repository
mkdir my-project && cd my-project
git init
This creates a hidden .git/ directory that tracks everything. You now have an empty repository on the main branch.
Initialize and Make Your First Commit
git init
echo "# My Project" > README.md
git add README.md
git commit -m "Initial commit"
Clone an Existing Repository
git clone https://github.com/user/repo.git
# Clone into a specific directory name
git clone https://github.com/user/repo.git my-local-name
# Clone a specific branch
git clone -b develop https://github.com/user/repo.git
# Shallow clone (only the latest commit — faster for large repos)
git clone --depth 1 https://github.com/user/repo.git
Clone via SSH (Recommended for Regular Use)
git clone git@github.com:user/repo.git
SSH cloning avoids having to type a password on every push. Set it up by adding your SSH key to GitHub/GitLab under Settings > SSH Keys.
3 Staging, Committing, and Viewing History
Checking What's Changed
git status # Overview: staged, unstaged, untracked files
git diff # Show unstaged changes line-by-line
git diff --staged # Show staged changes (what will be committed)
git diff HEAD # Show all changes since the last commit
Staging Changes
git add file.txt # Stage a specific file
git add src/ # Stage an entire directory
git add . # Stage everything in the current directory
git add -p # Interactively stage hunks (very useful)
The -p (patch) flag is one of the most powerful staging tools. It walks you through every changed chunk and asks whether to stage it. This lets you split unrelated work into separate, focused commits.
Unstaging Files
git restore --staged file.txt # Modern syntax
git reset HEAD file.txt # Older syntax (same result)
Committing
git commit -m "Add user authentication"
# Stage all tracked files and commit in one step
git commit -am "Fix typo in README"
# Open your editor to write a longer commit message
git commit
# Amend the last commit (message or files — before pushing)
git commit --amend -m "Better commit message"
git commit --amend --no-edit # Amend files without changing the message
Commit message best practices:
- Start with a capital letter
- Use the imperative mood: "Add feature", not "Added feature"
- Keep the subject line under 72 characters
- Add a blank line and then a longer description if needed
Viewing History
git log # Full log
git log --oneline # One line per commit
git log --oneline --graph --all # Visual branch graph
git log --oneline -10 # Last 10 commits
git log --author="Jane" # Filter by author
git log --since="2 weeks ago" # Filter by date
git log --grep="bugfix" # Filter by message keyword
git log -- path/to/file.txt # History for a specific file
git show <commit-hash> # Show a specific commit's changes
git show HEAD # Show the latest commit
Inspecting a File's History
git log -p file.txt # Full diff history for a file
git blame file.txt # Show who last changed each line
4 Branching and Merging
Branches are cheap and fast in Git. Use them aggressively.
Creating and Switching Branches
git branch # List local branches
git branch -a # List local and remote branches
git branch feature/login # Create a branch (stay on current branch)
git checkout feature/login # Switch to that branch
# Create and switch in one command (classic)
git checkout -b feature/login
# Create and switch in one command (modern, Git 2.23+)
git switch -c feature/login
# Switch to the previous branch
git checkout -
git switch -
Renaming and Deleting Branches
git branch -m old-name new-name # Rename a branch
git branch -d feature/login # Delete a merged branch
git branch -D feature/login # Force-delete an unmerged branch
git push origin --delete feature/login # Delete a remote branch
Merging
# Merge feature branch into main
git checkout main
git merge feature/login
Types of merges:
# Fast-forward merge (no merge commit — linear history)
git merge feature/login
# Create a merge commit even if fast-forward is possible
git merge --no-ff feature/login
# Squash all commits from the feature branch into one
git merge --squash feature/login
git commit -m "Add login feature"
Handling Merge Conflicts
Conflicts happen when the same lines were changed in both branches. Git marks them like this:
<<<<<<< HEAD
const greeting = "Hello";
=======
const greeting = "Hi there";
>>>>>>> feature/login
To resolve:
- Edit the file and remove the conflict markers, keeping the correct code
- Stage the resolved file:
git add file.txt - Complete the merge:
git commit
Useful conflict tools:
git mergetool # Open a visual merge tool
git merge --abort # Bail out and return to pre-merge state
git diff --diff-filter=U # List only conflicted files
5 Remote Operations
Managing Remotes
git remote -v # List remotes
git remote add origin https://github.com/user/repo.git
git remote rename origin upstream # Rename a remote
git remote remove upstream # Remove a remote
git remote set-url origin git@github.com:user/repo.git # Change URL
Fetching
git fetch downloads remote changes without touching your working directory or local branches. It's always safe.
git fetch # Fetch from all remotes
git fetch origin # Fetch from origin
git fetch origin main # Fetch a specific branch
After fetching, you can inspect what changed before merging:
git log HEAD..origin/main --oneline # Commits on remote not yet local
git diff HEAD origin/main # Diff between local and remote
Pulling
git pull is shorthand for git fetch followed by git merge (or git rebase if configured).
git pull # Pull from tracking remote branch
git pull origin main # Pull a specific branch
git pull --rebase # Pull and rebase instead of merge
git pull --ff-only # Only pull if it's a fast-forward (safe)
Pushing
git push # Push to tracking remote branch
git push origin main # Push to a specific remote/branch
git push -u origin feature/login # Push and set upstream tracking
git push --all # Push all branches
git push --tags # Push all tags
git push origin --delete feature/old # Delete a remote branch
Forcing a push (use with caution):
git push --force-with-lease # Safer force push — fails if remote has new commits
git push --force # Force push (can overwrite others' work)
Never force-push to a shared branch like main. Always prefer --force-with-lease over --force.
6 Advanced Operations
Git Rebase
Rebase replays your commits on top of another branch, resulting in a cleaner, linear history.
# Rebase current branch onto main
git checkout feature/login
git rebase main
# Interactive rebase — rewrite, squash, reorder, or drop commits
git rebase -i HEAD~3 # Rewrite the last 3 commits
git rebase -i main # Rewrite all commits since branching from main
In interactive rebase, each commit gets a prefix command:
pick— keep as-isreword— keep but edit the messagesquash— merge into previous commit (keeps both messages)fixup— merge into previous commit (discards this message)drop— delete this commit
git rebase --abort # Bail out of a rebase in progress
git rebase --continue # Continue after resolving a conflict
git rebase --skip # Skip a problematic commit
Git Cherry-Pick
Apply a specific commit from any branch onto your current branch:
git cherry-pick <commit-hash>
# Cherry-pick without committing (stage the changes only)
git cherry-pick --no-commit <commit-hash>
# Cherry-pick a range of commits
git cherry-pick abc123^..def456
# Continue after resolving a conflict
git cherry-pick --continue
# Abort a cherry-pick in progress
git cherry-pick --abort
main to a release branch, or pulling a single commit from an abandoned feature branch.
Git Stash
Stash saves your dirty working directory onto a stack so you can switch context and come back later.
git stash # Stash uncommitted changes
git stash push -m "WIP: login form" # Stash with a description
git stash list # List all stashes
git stash show stash@{0} # Show what's in a stash
git stash pop # Apply most recent stash and delete it
git stash apply stash@{1} # Apply a specific stash (keep it)
git stash drop stash@{0} # Delete a specific stash
git stash clear # Delete all stashes
# Stash including untracked files
git stash -u
# Stash everything including ignored files
git stash -a
Git Bisect
Bisect uses binary search to find the commit that introduced a bug.
git bisect start
git bisect bad # Current commit is broken
git bisect good v1.2.0 # This tag was working fine
# Git checks out a middle commit. Test it, then:
git bisect good # If this commit is fine
git bisect bad # If this commit is broken
# Git keeps narrowing until it finds the culprit.
# When done:
git bisect reset # Return to original HEAD
Automated bisect with a test script:
git bisect start
git bisect bad HEAD
git bisect good v1.2.0
git bisect run npm test # Runs until the bad commit is found
git bisect reset
Git Tags
git tag # List all tags
git tag v1.0.0 # Create a lightweight tag
git tag -a v1.0.0 -m "Release 1.0" # Create an annotated tag
git tag -a v1.0.0 <commit-hash> # Tag a specific past commit
git push origin v1.0.0 # Push a specific tag
git push origin --tags # Push all tags
git tag -d v1.0.0 # Delete a local tag
git push origin --delete v1.0.0 # Delete a remote tag
7 Undoing Changes
This is where people get nervous. Here's the clear mental model:
git restore— discard working directory changes (file-level)git reset— move the branch pointer backward (commit-level, affects local history)git revert— create a new commit that undoes a past commit (safe for shared branches)
Discarding Working Directory Changes
git restore file.txt # Discard unstaged changes to a file
git restore . # Discard all unstaged changes
git checkout -- file.txt # Same as restore (older syntax)
Unstaging Files
git restore --staged file.txt # Unstage a file (keep changes in working dir)
git reset HEAD file.txt # Same thing, older syntax
Undoing Commits with Reset
git reset HEAD~1 # Undo last commit, keep changes staged
git reset --soft HEAD~1 # Undo last commit, keep changes staged
git reset --mixed HEAD~1 # Undo last commit, unstage changes (default)
git reset --hard HEAD~1 # Undo last commit, discard all changes
git reset --hard HEAD # Discard all uncommitted changes
git reset <commit-hash> # Reset to any point in history
git reset on commits that haven't been pushed to a shared remote. For commits others have already pulled, use git revert.
Safe Undo with Revert
git revert HEAD # Create a commit undoing the last commit
git revert <commit-hash> # Undo a specific past commit
git revert HEAD~3..HEAD # Undo the last 3 commits
git revert --no-commit HEAD~3..HEAD # Stage the undo changes without committing
Revert is always safe because it adds to history rather than rewriting it.
Finding Lost Commits
If you accidentally lose commits (e.g., after a hard reset), the reflog saves you:
git reflog # Show every HEAD position for the last 90 days
git checkout HEAD@{3} # Go back to a specific reflog entry
git reset --hard HEAD@{3} # Restore branch to a reflog entry
The reflog is your safety net. Git almost never truly deletes data within the 90-day retention window.
8 Git Aliases and Productivity Tips
Defining Aliases
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.cm "commit -m"
git config --global alias.unstage "restore --staged"
git config --global alias.last "log -1 HEAD"
git config --global alias.lg "log --oneline --graph --all --decorate"
After setting these up:
git st # git status
git lg # Beautiful visual graph
git last # Show the last commit
Useful Log Aliases
git config --global alias.hist "log --pretty=format:'%h %ad | %s%d [%an]' --graph --date=short"
Shell Aliases (in ~/.bashrc or ~/.zshrc)
alias gs="git status"
alias ga="git add"
alias gc="git commit"
alias gp="git push"
alias gl="git log --oneline --graph --all"
alias gco="git checkout"
alias gcb="git checkout -b"
The .gitignore File
Tell Git which files to never track:
# Create a .gitignore in your project root
touch .gitignore
Common patterns:
node_modules/
.env
.env.local
__pycache__/
*.pyc
.DS_Store
dist/
build/
*.log
.vscode/
.idea/
Use gitignore.io to generate a complete .gitignore for your stack.
Global .gitignore
For files you never want tracked in any project:
git config --global core.excludesfile ~/.gitignore_global
Then put things like .DS_Store, .idea/, and .vscode/ in ~/.gitignore_global.
9 Common Gotchas and How to Fix Them
"I committed to the wrong branch"
# Move the last commit to a new branch
git checkout -b correct-branch
git checkout wrong-branch
git reset --hard HEAD~1
# Or cherry-pick it onto the right branch
git checkout correct-branch
git cherry-pick wrong-branch
git checkout wrong-branch
git reset --hard HEAD~1
"I need to change my last commit message"
git commit --amend -m "Correct message"
# Only do this if you haven't pushed yet
"I pushed something sensitive (passwords, API keys)"
- Immediately revoke the exposed credentials in whatever service issued them
- Remove the file from history with
git filter-branchor BFG Repo Cleaner - Force push the cleaned history
- Notify your team — everyone needs to re-clone
"My pull request has conflicts I need to fix"
git checkout feature/my-branch
git fetch origin
git rebase origin/main # Or: git merge origin/main
# Resolve conflicts in your editor
git add resolved-file.txt
git rebase --continue # Or: git commit
git push --force-with-lease # Safe push after rebase
"I accidentally deleted a branch"
git reflog # Find the commit the branch pointed to
git checkout -b recovered-branch <commit-hash>
"Git says my files are in a 'detached HEAD' state"
This means you checked out a specific commit rather than a branch. Your changes won't belong to any branch until you create one:
git checkout -b new-branch-name # Rescue your work into a new branch
"I want to undo a git merge"
# If you haven't pushed yet
git reset --hard ORIG_HEAD # ORIG_HEAD is saved before a merge
# If you have pushed
git revert -m 1 <merge-commit-hash> # -m 1 keeps the mainline parent
"My git pull is creating merge commits I don't want"
git pull --rebase # Rebase instead of merge
# Or configure it globally:
git config --global pull.rebase true
Checking Out a Remote Branch
git fetch origin
git checkout -b feature/login origin/feature/login
# Modern shortcut (Git will auto-track):
git checkout feature/login
git switch feature/login
Git Workflows at a Glance
Feature Branch Workflow (most common)
git checkout main && git pull
git checkout -b feature/my-feature
# ... make commits ...
git push -u origin feature/my-feature
# Open a pull request → review → merge
git checkout main && git pull
git branch -d feature/my-feature
Gitflow (for versioned releases)
Gitflow uses main, develop, feature/*, release/*, and hotfix/* branches. Good for products with explicit release cycles.
Trunk-Based Development
All developers commit directly to main (or very short-lived feature branches). Relies heavily on feature flags and CI. Common at companies with mature CI/CD pipelines.
Summary: The Commands That Matter Most Day-to-Day
For 90% of your daily work, you only need about a dozen commands:
git status
git add -p
git commit -m "..."
git pull --rebase
git push
git checkout -b feature/...
git merge main
git log --oneline --graph --all
git stash / git stash pop
git reset --soft HEAD~1
git diff --staged
Master these first. Then learn rebase, cherry-pick, bisect, and the undo commands as you encounter the situations that need them.
Free Resources
Git Cheat Sheet (Free PDF)
A single-page printable reference covering 60+ commands, organized by category with flags and examples. Keep it on your desk or pin it to your second monitor.
DevOps Starter Bundle ($39)
Ready to take your Git skills into a full DevOps workflow? The DevOps Starter Bundle includes:
- Git branching strategies and team workflows guide
- CI/CD pipeline templates (GitHub Actions, GitLab CI)
- Docker and container fundamentals
- Infrastructure-as-Code intro with Terraform
- Bash scripting for automation
Everything you need to go from writing code to shipping it reliably.