Git Essentials Cheatsheet
Master Git for version control: from initial setup to advanced branching, merging, and collaboration patterns.
## Git Essentials Cheatsheet
### Quick Overview
Git is a free and open-source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. It allows multiple developers to collaborate on a single project without overwriting each other's changes, track every modification made to the codebase, and revert to previous states if necessary. You'd reach for Git whenever you need to manage code history, collaborate with a team, or deploy changes reliably. This guide focuses on common commands and patterns in **Git 2.x**.
**Install Git (macOS):**
```bash
# Using Homebrew
brew install git
Install Git (Linux - Debian/Ubuntu):
sudo apt-get update
sudo apt-get install git
Install Git (Windows):
# Download from git-scm.com or use Winget
winget install --id Git.Git -e --source winget
Getting Started
The absolute minimum to set up Git and perform your first commit.
-
Configure User Information Sets your name and email, which will be attached to your commits.
# Set your global username git config --global user.name "Your Name" # Set your global email address git config --global user.email "[email protected]"You can verify your settings:
git config --list -
Initialize a New Repository Creates a new empty Git repository or reinitializes an existing one. This adds a
.gitdirectory to your project.# Navigate into your project directory cd my-awesome-project # Initialize a new Git repository git init -
Clone an Existing Repository Copies a Git repository from a remote location (e.g., GitHub) to your local machine.
# Clone a repository via HTTPS git clone https://github.com/user/repo.git # Clone a repository via SSH (if configured) git clone [email protected]:user/repo.git # Change into the cloned directory cd repo -
Your First Commit Add a file and commit it to your repository.
# Create a new file echo "console.log('Hello, Git!');" > app.js # Stage the file for commit git add app.js # Commit the staged file with a message git commit -m "feat: Add initial hello world app"
Core Concepts
A quick mental model for how Git works.
| Concept | Description |
|---|---|
| Repository | The .git directory that tracks all changes to your project’s files. |
| Commit | A snapshot of your repository at a specific point in time. Includes a message and author. |
| Branch | A lightweight movable pointer to a commit. Allows parallel development. |
| HEAD | A pointer to the current branch you are on. Represents your current working commit. |
| Remote | A version of your repository hosted on the internet or network, e.g., GitHub. |
| Index (Staging Area) | A temporary area where you prepare changes before committing them. |
| Merge | Combines changes from one branch into another, creating a new merge commit. |
| Rebase | Rewrites commit history by moving a series of commits to a new base commit. |
Essential Commands / API / Syntax
The 80/20 of Git commands, organized by common tasks.
Checking Status & Viewing Changes
# Show the working tree status (untracked, modified, staged files)
git status
# Show changes between the working directory and the staging area
git diff
# Show changes between the staging area and the last commit
git diff --staged # or git diff --cached
Staging & Committing Changes
# Add all new and modified files in the current directory to the staging area
git add .
# Add a specific file to the staging area
git add my-file.txt
# Add all files in a specific directory
git add src/
# Commit staged changes with a message
git commit -m "feat: Add new feature"
# Commit staged changes and immediately open an editor for a longer message
git commit
# Stage all tracked changes and commit them in one step
git commit -am "fix: Fix a bug" # 'a' for all tracked changes
Branching & Merging
# List all local branches
git branch
# List all local and remote branches
git branch -a
# Create a new branch
git branch new-feature
# Switch to an existing branch (legacy command)
git checkout new-feature
# Switch to an existing branch (preferred in Git 2.23+)
git switch new-feature
# Create and switch to a new branch
git checkout -b new-feature # legacy
git switch -c new-feature # preferred
# Merge another branch into your current branch
git merge feature-branch
# Delete a local branch (only if it's already merged)
git branch -d old-branch
# Force delete a local branch (even if not merged)
git branch -D old-branch
Working with Remotes
# List all configured remotes
git remote -v
# Add a new remote repository
git remote add origin https://github.com/user/repo.git
# Fetch all new branches and commits from the remote
git fetch origin
# Pull changes from a remote branch into your current branch (fetch + merge)
git pull origin main
# Push your local branch to a remote repository
git push origin main
# Push your local branch and set the remote tracking upstream
git push -u origin feature-branch # sets 'feature-branch' on 'origin' as the upstream
Inspecting History
# Show commit history (most recent first)
git log
# Show a condensed log
git log --oneline
# Show a graphical representation of the commit history
git log --graph --oneline --decorate
# Show changes introduced by a specific commit
git show <commit-hash>
Undoing Changes
# Discard unstaged changes in a specific file (Git 2.23+)
git restore my-file.txt
# Discard all unstaged changes in the current directory (Git 2.23+)
git restore .
# Unstage a file (keep changes in working directory)
git restore --staged my-file.txt # Git 2.23+
git reset HEAD my-file.txt # legacy
# Create a new commit that undoes the changes from a previous commit
git revert <commit-hash>
# Move the branch HEAD to a prior commit, discarding subsequent commits (DANGEROUS if pushed!)
git reset --hard <commit-hash>
# Move the branch HEAD to a prior commit, but keep changes in staging area
git reset --soft <commit-hash>
# Move the branch HEAD to a prior commit, keep changes in working directory (unstaged)
git reset --mixed <commit-hash> # This is the default reset behavior
Common Patterns
Practical recipes for common Git workflows.
1. Contributing to an Existing Project
# 1. Clone the repository
git clone https://github.com/project/repo.git
cd repo
# 2. Create a new feature branch for your work
git switch -c my-new-feature
# 3. Make changes to files
# ... edit files ...
# 4. Stage and commit your changes
git add .
git commit -m "feat: Implement amazing new feature"
# 5. Pull latest changes from main branch to resolve any conflicts (optional but recommended)
git switch main
git pull origin main
git switch my-new-feature
git merge main # resolve conflicts if any
# 6. Push your feature branch to the remote
git push -u origin my-new-feature
# 7. Open a Pull Request (PR) on GitHub/GitLab/Bitbucket
2. Stashing Local Changes
Temporarily save changes you don’t want to commit yet, to switch branches or pull updates.
# Save your current uncommitted changes (staged and unstaged)
git stash save "Work in progress on feature X"
# List all stashes
git stash list
# Apply the most recent stash and remove it from the stash list
git stash pop
# Apply a specific stash (e.g., stash@{1}) and keep it in the list
git stash apply stash@{1}
# Delete all stashes
git stash clear
3. Amending the Last Commit
Change the message or add more files to the most recent commit.
# Make changes or stage additional files
# git add new-file.txt
# Amend the last commit with current staged changes and/or a new message
# This rewrites the commit history, use with caution if already pushed.
git commit --amend -m "fix: Update message and add new file"
# If you only want to change the message, without altering files:
git commit --amend --no-edit
Gotchas & Tips
Stuff that trips people up, and how to avoid it.
-
Detached HEAD State: When you
checkouta specific commit hash (not a branch), yourHEADpoints directly to that commit, not to a branch. You can look around, but if you commit, those commits aren’t part of any branch unless you create one from that point.# You might see this after `git checkout <commit-hash>` git checkout <commit-hash> # To fix: create a new branch from this commit git switch -c new-temp-branch -
Merge Conflicts: These happen when Git cannot automatically reconcile changes between two branches.
- Git marks conflicts in your files with
<<<<<<<,=======,>>>>>>>. - Manually edit the file to resolve the conflict.
git add <conflicted-file>git commit -m "Resolve merge conflict"
- Git marks conflicts in your files with
-
Force Pushing (
git push --force): This overwrites the remote branch history with your local history. Use with extreme caution, especially on shared branches likemain, as it can erase other contributors’ work. Only use if you absolutely know what you’re doing (e.g., after agit rebaseon a private branch). -
Ignoring Files (
.gitignore): Create a.gitignorefile in your repository’s root to tell Git which files/directories to ignore.# .gitignore example /node_modules/ # Ignore node_modules directory *.log # Ignore all .log files .env # Ignore .env file build/ # Ignore build directory -
Large Files (Git LFS): Git is not designed for large binary files (images, videos, executables). For these, use Git Large File Storage (LFS) to keep your repository lean.
# Install Git LFS (one-time setup) git lfs install # Track specific file types git lfs track "*.psd" git lfs track "videos/*.mp4" # Stage and commit .gitattributes (generated by `git lfs track`) git add .gitattributes git commit -m "feat: Configure Git LFS for PSD files"
Next Steps
- Official Git Documentation: The definitive source for all things Git.
- Pro Git Book: A comprehensive and freely available book that covers Git in depth, from basics to advanced topics.
- z2h.fyi/cheatsheets/github-cli: Learn how to interact with GitHub from your terminal.
Source: z2h.fyi/cheatsheets/git-cheatsheet — Zero to Hero cheatsheets for developers.