Back to blog
22 min read

Git and GitHub: A Practical Guide, from First Commit to Advanced Workflows

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:

  1. Create or clone a repository.
  2. Edit files on your computer.
  3. Stage the changes you want.
  4. Commit them locally.
  5. Push commits to a remote when you want to share.
  6. 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:

Git working directory staging area and repository

  • 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

  1. Editing after git add. The new edits are not staged. Run git add again.
  2. Thinking git add saves a commit. It only prepares one. You still need git commit.
  3. Committing without reviewing. Check git status and git diff --cached to avoid unrelated files or secrets.
  4. 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

CommandWhat it does
git add <file>Stage a file
git add -AStage additions, modifications, and deletions repo-wide
git add -uStage modifications and deletions of tracked files only
git add -pStage 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/
  • *.log matches files ending in .log.
  • build/ matches directories named build; /build/ only at the root.
  • !name re-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 origin downloads new commits and updates remote-tracking branches, but leaves your current branch alone.
  • git pull fetches 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.

Fast Forward Merge

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.

Three-way merge

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 Rebase

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.

MergeRebase
Joins histories, often with a merge commitReplays commits on a new base
Preserves existing commit IDsGives replayed commits new IDs
Shows where branches were integratedOften produces linear history
Usually fine for shared historyBest 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 squash commits before and after

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:

Git merge conflict markers explained

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:

  1. Open each conflicted file.
  2. Decide what stays: either side, or a blend of both.
  3. Delete all conflict markers.
  4. Run tests.
  5. Stage the file with git add.
  6. Finish: git commit for a merge, git rebase --continue for 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

Git 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.

SituationCommandEffect
Discard unstaged edits to a tracked filegit restore fileRestores from the index
Unstage a filegit restore --staged fileResets index entry to HEAD
Undo a shared commit safelygit revert <commit>Adds a new commit reversing it
Undo last local commit, keep changes stagedgit reset --soft HEAD~1Moves branch pointer only
Undo last local commit, keep changes unstagedgit reset --mixed HEAD~1Default mode
Save work temporarilygit stashStores changes for later
Remove untracked filesgit cleanDeletes them; preview first
  • restore handles file content. It can discard uncommitted edits permanently.
  • reset moves your branch pointer. --hard also wipes the index and working tree, so avoid it casually. Use reset on local, unshared history.
  • revert is the safe choice for published commits because it adds history instead of rewriting it. Reverting a merge commit needs -m to choose a mainline parent, so study the history first.
  • stash: git stash push -m "WIP", then git stash apply (keeps the stash) or git stash pop (removes it on success). Add -u to include untracked files.
  • clean: always preview with git clean -nd before the destructive git clean -fd. Adding -x also 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:

  1. Keep main deployable.
  2. Create a short-lived branch.
  3. Commit and push.
  4. Open a pull request.
  5. Let CI run and request review.
  6. 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 with git 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 --full is 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 status before anything destructive, especially reset --hard, clean, and force-pushing.

Quick Reference

GoalCommand
Start a repogit init
Stage / review / commitgit add, git diff --cached, git commit -m
See historygit log --oneline --graph --all
Download vs. integrategit fetch vs. git pull
Merge a branchgit merge <branch>
Rebase onto a branchgit rebase <branch>
Combine recent commitsgit rebase -i HEAD~N
Apply one commitgit cherry-pick <hash>
Find lost positionsgit reflog
Reverse a published commitgit revert <hash>
Save work temporarilygit stash push -m "msg"
Release taggit tag -a v1.0.0 -m "msg"
Track large filesgit lfs track "*.ext"