Imagine working on a project for several weeks. You add features, fix bugs, try a few experiments, and rewrite old code. Then something breaks. Which change caused it? What did the code look like yesterday? Can you go back without losing today’s work?
Git exists to answer exactly these questions. This guide takes you from “what is version control?” to confidently merging, rebasing, recovering from mistakes, and shipping releases. Every section builds on the one before it, and every concept comes with a command you can try in a throwaway repository.
Part 1: Why Version Control?
Version control is a system that records changes to files over time, so you can inspect earlier versions, see what changed, and recover old states.
A software project is not a fixed set of files. It evolves: a basic app, then login, then a login bug fix, then a dashboard, then a regression to investigate. Version control lets you mark meaningful checkpoints along that journey.
The “final-final” problem
Most of us start with manual backups:
my-project/
├── my-project-final/
├── my-project-final-new/
├── my-project-final-latest/
└── my-project-final-latest-fixed/
This breaks down fast. Which folder is correct? What changed between them? Who edited which file? How do you combine a teammate’s work safely? Version control replaces this guesswork with a structured history.
What version control gives you
- Change tracking: see exactly what differs between two versions, not whole folders.
- Recovery: if a change introduces a bug, inspect history and pick a recovery strategy.
- Collaboration: many developers can work on one project and integrate their work in a controlled way.
- History: answer who changed something, when, what, and (through commit messages) why.
- Safe experiments: try ideas on isolated branches without touching the main line of work.
Key takeaway: version control helps you manage change, preserve history, collaborate, and recover from mistakes.
Part 2: Git vs. GitHub
These two names are often used interchangeably, but they are different things.
Git is a free, open-source, distributed version control system, created by Linus Torvalds in 2005. It runs on your computer and tracks changes in your files. You do not need the internet or an account to use it.
GitHub is a hosting platform for Git repositories. It adds a shared remote home for your code, plus pull requests, code review, issues, and automated checks.
A good mental model: Git is the engine; GitHub is the garage where teams park, share, and review their work.
A typical flow looks like this:
- Create or clone a repository.
- Edit files on your computer.
- Stage the changes you want.
- Commit them locally.
- Push commits to a remote when you want to share.
- Collaborate through branches and pull requests.
Developer's Computer
┌──────────────────────────┐
│ Working Tree │
│ │ git add │
│ ▼ │
│ Staging Area │
│ │ git commit │
│ ▼ │
│ Local Repository │
└────────────┬─────────────┘
│ git push
▼
┌──────────────────────────┐
│ GitHub Remote │
│ Pull Requests · Reviews │
│ Automated Checks │
└──────────────────────────┘
This is simplified. Git also supports fetching, merging, rebasing, and recovery, all covered below.
Part 3: Installing Git
Windows: download the installer from Git for Windows and use Git Bash, PowerShell, or Command Prompt. If you develop inside WSL, install Git separately there:
sudo apt update
sudo apt install git
macOS:
xcode-select --install
# or
brew install git
Linux: use your package manager.
sudo apt update && sudo apt install git # Ubuntu / Debian
sudo dnf install git # Fedora
sudo pacman -S git # Arch
Verify the install:
git --version
Then tell Git who you are. These values are stamped on your commits; they are not your GitHub login.
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
Part 4: Your First Repository and Commit
Let’s make something real.
mkdir first-git-project
cd first-git-project
git init
Git creates a repository in the current folder. (Use git init -b main to set the initial branch name immediately.) Your files stay on your machine; GitHub is not involved.
Create a file and check the status:
echo "# My First Git Project" > README.md
git status
Git reports README.md as untracked: it sees the file but is not recording it in history yet.
The three areas of Git
This is the single most important mental model:

- Working directory: your files and current edits.
- Staging area: the changes you have chosen for the next commit.
- Repository history: commits already saved.
The staging area lets you craft commits deliberately instead of dumping every edit into one.
Stage, then commit
git add README.md
git status # now under "Changes to be committed"
git diff --cached # review exactly what will be saved
git commit -m "Add project README"
git add stages the file’s current content. It does not create a commit. The commit saves the staged snapshot into local history.
Inspect the result:
git log --oneline
git show HEAD
Now change the file and commit again:
echo "Learning Git step by step." >> README.md
git diff # unstaged changes
git add README.md
git commit -m "Add project description"
git log --oneline # two commits
A good commit message explains the change. “Add project README” beats “changes” or “first commit”.
Four classic beginner mistakes
- Editing after
git add. The new edits are not staged. Rungit addagain. - Thinking
git addsaves a commit. It only prepares one. You still needgit commit. - Committing without reviewing. Check
git statusandgit diff --cachedto avoid unrelated files or secrets. - Expecting commits to appear on GitHub. Commits are local until you push.
Writing Commit Messages That Mean Something (feat, fix, chore and friends)
A commit message is a note to your future self and your teammates. “update stuff” tells nobody anything; “fix: prevent crash when the cart is empty” tells them everything at a glance. Many teams follow the Conventional Commits format:
text type(scope): short description
[optional body: what and why]
[optional footer: issue links, breaking changes]
The scope is optional and names the area you touched, like auth or api.
Type Use it for Example feat A new feature feat(auth): add Google sign-in fix A bug fix fix(cart): handle empty cart on checkout docs Documentation only docs: add setup steps to README style Formatting, whitespace, semicolons (no logic change) style: format files with Prettier refactor Restructuring code without changing behavior refactor(api): split user service into modules perf Performance improvements perf(search): cache repeated queries test Adding or fixing tests test(auth): cover expired-token case build Build system or dependency changes build: upgrade webpack to v5 ci CI/CD configuration ci: run tests on pull requests chore Routine maintenance that doesn’t fit above chore: update .gitignore revert Undoing an earlier commit revert: revert “feat(auth): add Google sign-in”
A quick way to choose between the confusing ones: if users would notice the change, it is feat or fix. If only developers would notice, it is probably refactor, test, build, ci, or chore.
Habits that make messages good:
Use the imperative mood: “add login form”, not “added” or “adds”. Read it as “If applied, this commit will… add login form.” Keep the subject short, around 50 characters (72 at most), with no trailing period. Explain why in the body when the reason isn’t obvious. The diff already shows what changed. One logical change per commit. If your message needs “and”, consider two commits (this is where git add -p helps). Reference issues in the footer, for example Closes #42.
Breaking changes are flagged with a ! after the type, or a BREAKING CHANGE: footer:
text feat(api)!: rename /users endpoint to /accounts
BREAKING CHANGE: clients must update requests to /accounts.
The format pays off beyond readability. Tools can generate changelogs from it, and it lines up with semantic versioning from Part 13: fix suggests a PATCH release, feat a MINOR release, and a breaking change a MAJOR release.
Before and after:
text Bad: fixed stuff Bad: WIP Good: fix(login): show error message on wrong password Good: chore: remove unused dependencies
Conventions like this are a team agreement. Check whether your project already uses one before introducing your own.
Part 5: How Git Actually Stores Things
Commands like commit, branch, and merge make much more sense once you know what they operate on. Run git init and Git creates a hidden .git/ directory: the repository’s internal database. Look, but do not hand-edit it.
ls -la .git
The four object types
Blob. Stores a file’s content, not its name or location.
echo "Hello Git" > hello.txt
git add hello.txt
git ls-files -s # shows the blob ID (a hash)
Tree. Represents a directory: it maps names and file modes to blobs or other trees.
Commit. A snapshot: it points to a root tree and stores the author, committer, timestamp, message, and parent commit(s).
git commit -m "Add hello file"
git cat-file -p HEAD
Tag. A name for a specific point in history, usually a release like v1.0.0. Annotated tags are stored as their own objects with a message.
Here is how they connect:
Commit
|
v
Root Tree
|
+--> Blob: README.md
+--> Blob: app.py
+--> Tree: src/
|
+--> Blob: utils.py
Objects are content-addressed: their ID is derived from their type, size, and content (shown as a SHA-1 hash in most repositories; SHA-256 is also supported). Git does not store a full separate copy of every file for every commit. Identical content reuses the same blob, and Git packs and compresses objects to save space.
What is HEAD?
HEAD marks where you currently are. Normally it points to a branch, and the branch points to a commit.
HEAD -> main -> Commit C
cat .git/HEAD # ref: refs/heads/main
Detached HEAD happens when HEAD points straight at a commit rather than a branch:
git switch --detach <commit-hash>
It is fine for looking at old code. But commits you make while detached can become hard to find once you switch away, unless you create a branch or tag to keep them. Return with git switch main.
Part 6: Everyday Core Skills
Staging precisely
| Command | What it does |
|---|---|
git add <file> | Stage a file |
git add -A | Stage additions, modifications, and deletions repo-wide |
git add -u | Stage modifications and deletions of tracked files only |
git add -p | Stage selected pieces (“hunks”) of a file |
git restore --staged <file> | Unstage without discarding edits |
git add -p is a quiet superpower: if one file holds two unrelated fixes, you can commit them separately.
Reading history
git log --oneline --graph --all
git show <hash>
git diff <commit1> <commit2>
Keeping the repo clean with .gitignore
A .gitignore lists patterns for untracked files Git should ignore:
# Python
__pycache__/
*.py[cod]
.venv/
# Environment files
.env
.env.*
!.env.example
# Node.js
node_modules/
# Build output
dist/
build/
*.logmatches files ending in.log.build/matches directories namedbuild;/build/only at the root.!namere-includes something previously ignored.
Gotcha: .gitignore does not untrack files that are already tracked. To stop tracking while keeping your local copy:
git rm --cached .env
git commit -m "Stop tracking environment file"
If that file held a real secret, rotate the secret immediately. Removing it from the latest commit does not erase it from earlier history.
Bonus: Git does not track empty directories, so people drop an empty .gitkeep file inside to keep them. That is a convention, not a Git feature.
Remotes and synchronization
A remote is a named reference to another repository, usually on GitHub. origin is the default name given when you clone, but it is just a convention.
git clone https://github.com/OWNER/REPOSITORY.git
git remote -v
git remote add origin <url>
git push -u origin main # publish and set the upstream
An upstream branch is the remote-tracking branch linked to your local one (local main and origin/main). Once set, git pull and git push need no extra arguments.
Fetch vs. pull is a classic confusion:
git fetch origindownloads new commits and updates remote-tracking branches, but leaves your current branch alone.git pullfetches and then integrates (merge or rebase, depending on configuration).
Fetching first lets you look before you leap:
git fetch origin
git log --oneline HEAD..origin/main # commits you don't have yet
By convention, origin is your clone or fork, while upstream is often the original project when you contribute through a fork:
git remote add upstream https://github.com/ORIGINAL-OWNER/REPOSITORY.git
When both your branch and the remote have commits the other lacks, the histories have diverged:
C local main
/
A --- B
\
D origin/main
You must integrate them (merge or rebase) before a normal push works.
A typical daily loop
git status # where am I?
git diff # what did I change?
git add src/app.py # choose what to include
git diff --cached # confirm exactly what's staged
git commit -m "Improve application validation"
git fetch origin # see what others did
git pull # integrate per your team's workflow
git push # publish
Part 7: Branches and Merging
A branch is just a movable pointer to a commit, which is why branching in Git is cheap.
git branch # list
git switch -c feature/dashboard # create and switch
git switch main
git branch -d feature/login # delete a merged branch
git branch -D force-deletes even unmerged work, so use it only when you are sure.
A merge integrates one branch’s history into another. Git compares commit ancestry; it does not blindly overwrite folders.
Fast-forward merge
When the target branch has not moved since you branched, Git simply slides the pointer forward.

git switch main
git merge feature
No new commit is created.
Three-way merge
When both branches have moved on, Git uses the two tips plus their common ancestor and creates a merge commit with two parents.

Want a visible merge commit even when a fast-forward is possible? Use git merge --no-ff feature. Whether to do that is a team convention.
Changed your mind mid-merge? git merge --abort. (Once the merge is committed, use git revert or another recovery method instead.)
Key distinction: a fast-forward moves a pointer; a three-way merge creates a new commit that joins two histories.
Part 8: Rebase and Squash
Rebase
Rebase replays your commits on top of a different base, usually giving a straight-line history. Suppose main moved ahead while you worked on feature:

git switch feature
git rebase main
A---B---E---F---C'---D' feature
C' and D' carry the same changes but are new commits with new IDs.
| Merge | Rebase |
|---|---|
| Joins histories, often with a merge commit | Replays commits on a new base |
| Preserves existing commit IDs | Gives replayed commits new IDs |
| Shows where branches were integrated | Often produces linear history |
| Usually fine for shared history | Best on private, unshared commits |
Rule of thumb: rebase private work to make it cleaner; merge when preserving shared integration history matters more.
If a replayed commit conflicts, resolve it, git add the file, then git rebase --continue. To bail out, git rebase --abort. (--skip drops the current commit, so only use it when you are sure that change is no longer needed.)
Safety: avoid rebasing commits others have built on without coordinating. If a coordinated rewrite requires a force push, prefer:
git push --force-with-lease
It refuses to overwrite remote work you have not seen, which makes it safer than --force.
Squashing
Squashing combines several commits into one, perfect for cleaning up “fix typo”, “try again”, and “address review comments” before a pull request.

git rebase -i HEAD~4
pick a1b2c3 Add user form
squash d4e5f6 Fix form validation
squash 123abc Update form styles
squash 456def Add form tests
Keep the first as pick, mark the rest squash (combine and edit the message) or fixup (combine and discard the message). Interactive rebase also offers reword, edit, and drop.
GitHub’s Squash and merge button is related but different: the target branch receives one combined commit, while the original commits may remain on the feature branch.
Do not squash commits other people already depend on without coordination, since it rewrites history.
Part 9: Resolving Merge Conflicts
A conflict is not a failure. It is Git saying, “two changes overlap; you decide what the final content should be.” It happens when branches edit the same lines, or when one deletes a file the other changed.
Start with git status to see affected files. A conflicted file looks like this:

The top half is the current side, the bottom half the incoming side. During a rebase the “ours/theirs” labels can feel reversed, so read the actual code instead of trusting labels.
Resolution steps:
- Open each conflicted file.
- Decide what stays: either side, or a blend of both.
- Delete all conflict markers.
- Run tests.
- Stage the file with
git add. - Finish:
git commitfor a merge,git rebase --continuefor a rebase.
To abandon: git merge --abort or git rebase --abort. You can also run git mergetool if you have one configured.
Common mistakes: leaving markers in code, picking a side without understanding it, forgetting to stage the resolution, assuming a conflict-free merge is automatically correct, and using git reset --hard to escape (which can destroy uncommitted work).
Part 10: Cherry-Pick, Reflog, and Recovery
Cherry-pick

Apply just one commit’s change to your current branch:
git switch release
git cherry-pick <commit-hash>
It creates a new commit with a different ID. Great for pulling a single bug fix into a release branch. On conflict, resolve and run git cherry-pick --continue, or --abort to cancel.
Reflog: your safety net
The reflog records recent movements of HEAD and branch tips locally. It can help after an accidental reset or rebase.
git reflog
git show <commit-hash> # inspect the candidate
git branch recovery <commit-hash> # preserve it
Reflog entries are local and expire, so they are not a backup.
Common rescue scenarios:
- Moved a branch backward by accident: find the old position in the reflog and branch from it.
- Committed to the wrong branch: cherry-pick the commit onto the right branch, then carefully clean up the original.
- Lost uncommitted changes: often unrecoverable if never committed or stashed. Check editor history or backups.
Part 11: Undoing Things Correctly
Git has several undo tools because “undo” means different things depending on where the change lives.
| Situation | Command | Effect |
|---|---|---|
| Discard unstaged edits to a tracked file | git restore file | Restores from the index |
| Unstage a file | git restore --staged file | Resets index entry to HEAD |
| Undo a shared commit safely | git revert <commit> | Adds a new commit reversing it |
| Undo last local commit, keep changes staged | git reset --soft HEAD~1 | Moves branch pointer only |
| Undo last local commit, keep changes unstaged | git reset --mixed HEAD~1 | Default mode |
| Save work temporarily | git stash | Stores changes for later |
| Remove untracked files | git clean | Deletes them; preview first |
restorehandles file content. It can discard uncommitted edits permanently.resetmoves your branch pointer.--hardalso wipes the index and working tree, so avoid it casually. Use reset on local, unshared history.revertis the safe choice for published commits because it adds history instead of rewriting it. Reverting a merge commit needs-mto choose a mainline parent, so study the history first.stash:git stash push -m "WIP", thengit stash apply(keeps the stash) orgit stash pop(removes it on success). Add-uto include untracked files.clean: always preview withgit clean -ndbefore the destructivegit clean -fd. Adding-xalso removes ignored files like local environments.
Part 12: Team Workflows
A branching strategy defines how a team isolates work and integrates it.
GitHub Flow is simple and popular:
- Keep
maindeployable. - Create a short-lived branch.
- Commit and push.
- Open a pull request.
- Let CI run and request review.
- Merge after approval.
git switch main
git pull
git switch -c feature/user-profile
# make changes
git add .
git commit -m "Add user profile page"
git push -u origin feature/user-profile
Git Flow adds long-lived develop, release/*, and hotfix/* branches. It suits scheduled releases but can be heavy for teams that deploy continuously.
Trunk-based development integrates small changes into main very frequently, using short-lived branches and feature flags. It needs solid automated tests.
Pick one branch-naming convention and stick to it:
feature/user-profile fix/login-validation docs/git-guide
refactor/payment-service hotfix/session-expiry
Part 13: Tags, Releases, and Versioning
A tag names a point in history. For official releases, prefer annotated tags, which record the tagger, date, and message.
git tag -a v1.0.0 -m "Release version 1.0.0"
git show v1.0.0
git push origin v1.0.0
Use git push origin --tags carefully, since it publishes every local tag. Delete a local tag with git tag -d; deleting remote tags should be coordinated.
Semantic versioning uses MAJOR.MINOR.PATCH (for example 2.4.1): MAJOR for incompatible changes, MINOR for backward-compatible features, PATCH for backward-compatible fixes. Pre-release labels like 2.0.0-rc.1 mark release candidates.
A Git tag is a point in history. A GitHub Release is a platform entry attached to a tag, with release notes and downloadable assets. Treat published tags as stable: moving them confuses CI systems and users.
Part 14: Troubleshooting and Large Repositories
When something feels off, look before you fix:
git status
git log --oneline --graph --decorate --all
git remote -v
git branch -vv
- Push rejected:
git fetch origin, inspect withgit log --oneline HEAD..origin/main, integrate via merge or rebase, resolve conflicts, then push. - Wrong branch:
git branch --show-current, then switch. If you already committed, recover deliberately rather than deleting history. - Can’t switch with uncommitted changes: commit, stash, or deliberately discard. Do not throw away work just to silence an error.
- Suspected corruption:
git fsck --fullis diagnostic, not a fix. Back up first.
Maintenance: git count-objects -vH reports storage, git gc packs loose objects and prunes eligible unreachable ones, and git maintenance run runs scheduled tasks. You rarely need these in normal work, and pruning can make unreachable objects unrecoverable.
Git LFS and big repos
Git is great at text. Large, frequently changing binaries bloat the repo and slow cloning. Git LFS keeps big file contents in separate storage while Git tracks small pointer files.
git lfs install
git lfs track "*.psd"
git add .gitattributes design.psd
git commit -m "Track design assets with Git LFS"
git push
git lfs ls-files
Limits to know: LFS does not shrink files already in history (migrating needs git lfs migrate and a history rewrite), your host must support it, and storage or bandwidth caps may apply.
Two more tools for huge repositories:
git sparse-checkout init --cone
git sparse-checkout set src docs # check out only some folders
git clone --filter=blob:none <url> # partial clone: fetch file contents on demand
Best Practices Checklist
- Use version control from day one.
- Commit meaningful changes with messages that explain why.
- Never commit passwords, API keys, or tokens.
- Use branches for isolated work; review changes before merging.
- Keep generated files and dependencies out of the repo.
- Use tags for releases.
- Run
git statusbefore anything destructive, especiallyreset --hard,clean, and force-pushing.
Quick Reference
| Goal | Command |
|---|---|
| Start a repo | git init |
| Stage / review / commit | git add, git diff --cached, git commit -m |
| See history | git log --oneline --graph --all |
| Download vs. integrate | git fetch vs. git pull |
| Merge a branch | git merge <branch> |
| Rebase onto a branch | git rebase <branch> |
| Combine recent commits | git rebase -i HEAD~N |
| Apply one commit | git cherry-pick <hash> |
| Find lost positions | git reflog |
| Reverse a published commit | git revert <hash> |
| Save work temporarily | git stash push -m "msg" |
| Release tag | git tag -a v1.0.0 -m "msg" |
| Track large files | git lfs track "*.ext" |