Git

How Git works — snapshots and the object model (blobs, trees, commits), the three areas, branching and merging, rebase, resolving conflicts, remotes, undoing mistakes with reset, revert and reflog, and useful power tools.

Beginner 4 min readLesson 2 of 9 Interview Q&A

Git is a distributed version control system: every clone has the full history, commits are local and fast, and collaboration happens by exchanging commits. Understanding its simple internal model makes every command make sense. (Team workflows — trunk-based development, pull requests — are in Version control workflows.)

Snapshots, not diffs

Each commit records a snapshot of the whole project (efficiently — unchanged files are shared), plus metadata and a pointer to its parent commit(s). History is a directed acyclic graph of commits.

The object model

Everything is stored in .git/objects, addressed by the SHA hash of its content (content-addressable storage):

ObjectContains
BlobFile contents (no name)
TreeA directory: names → blobs and subtrees
CommitRoot tree, parent commit(s), author, committer, message
Tag (annotated)Points to a commit with a message and signature
parentmaincommit c3commit c2treeblob READMEblob app.py

A branch is just a movable pointer (a 41-byte file) to a commit. HEAD points to the current branch. Creating a branch is therefore instant, and changing any byte of history changes every later hash — which is why history is tamper-evident.

The three areas

AreaWhatCommands
Working directoryFiles you edit—
Staging area (index)The snapshot you're preparing for the next commitgit add, git restore --staged
RepositoryCommitted historygit commit
Shell
git init / git clone <url>
git status                      # what changed, what's staged
git diff                        # working dir vs staged
git diff --staged               # staged vs last commit
git add file.py                 # stage a file
git add -p                      # stage hunk by hunk (great for clean commits)
git commit -m "Add retry to payment client"
git log --oneline --graph --all # visual history
git show <commit>               # one commit's changes

Branching and merging

Shell
git switch -c feature/search    # create and switch to a new branch
# … commit work …
git switch main
git merge feature/search
  • Fast-forward merge: if main hasn't moved, Git just moves the pointer forward — no merge commit.
  • Three-way merge: if both branches have new commits, Git combines them using their merge base (common ancestor) and creates a merge commit with two parents.
Before:          After merge:
A─B─C  main      A─B─C─────M  main
   \                \     /
    D─E feature      D─E─┘

Rebase

Rebase replays your commits on top of another branch, creating new commits with new hashes and a linear history:

Before:                    git rebase main (on feature):
A─B─C  main                A─B─C  main
   \                              \
    D─E feature                    D'─E'  feature
Shell
git switch feature
git rebase main                 # replay D, E onto C
git rebase -i HEAD~4            # interactive: squash, reorder, reword, drop commits
git pull --rebase               # rebase local commits on top of fetched ones
MergeRebase
Preserves exact history, including when branches divergedLinear, cleaner history
Non-destructiveRewrites commits (new hashes)
Merge commits can clutter historyConflicts may need resolving commit by commit

Resolving conflicts

When both sides changed the same lines, Git stops and marks the file:

<<<<<<< HEAD
timeout = 30
=======
timeout = 60
>>>>>>> feature/slow-api

Edit to the correct result, remove the markers, git add the file, then git commit (merge) or git rebase --continue. git merge --abort / git rebase --abort back out. Enable git config --global rerere.enabled true to remember resolutions.

Remotes

Shell
git remote -v                   # list remotes (origin = where you cloned from)
git fetch                       # download new commits; doesn't change your branches
git pull                        # fetch + merge (or rebase) into the current branch
git push -u origin feature/x    # publish a branch and set upstream
git branch -vv                  # local branches with their upstream status

origin/main is a remote-tracking branch: your local record of where main was on the remote at the last fetch.

Undoing things

SituationCommand
Discard unstaged changes to a filegit restore file
Unstage a filegit restore --staged file
Fix the last commit (message or forgotten file)git commit --amend (before pushing)
Undo a pushed commit safelygit revert <commit> — adds a new inverse commit
Move the branch back, keep changes stagedgit reset --soft HEAD~1
Move back, keep changes unstagedgit reset HEAD~1 (mixed, default)
Move back and discard changesgit reset --hard HEAD~1 (destructive)
Recover "lost" commitsgit reflog then git switch -c rescue <hash>
Shelve work temporarilygit stash / git stash pop

The reflog records every position HEAD has been at for ~90 days — after a bad reset or rebase, your commits are almost always still recoverable.

Power tools

Shell
git bisect start; git bisect bad; git bisect good v1.2    # binary-search for the commit that broke something
git bisect run ./test.sh                                    # …automatically
git blame -L 40,60 app.py       # who last changed each line (and in which commit)
git log -S "retry_count"        # commits that added or removed a string ("pickaxe")
git cherry-pick <commit>        # apply one commit onto the current branch
git worktree add ../hotfix main # a second working directory for another branch
git tag -a v1.4.0 -m "Release"  # annotated release tag
git clean -fdn                  # preview deleting untracked files (-f to do it)

Good practice

  • Small, focused commits with messages explaining why: an imperative summary line ≤ 50 chars ("Add retry to payment client"), a blank line, then details. Conventional Commits (feat:, fix:) enable automated changelogs (Semantic versioning).
  • A .gitignore for build output, dependencies and secrets. Never commit secrets — if you do, rotate them; deleting the file doesn't remove history.
  • Large binaries: Git LFS.
  • Sign commits/tags (GPG or SSH signing) where provenance matters.
Key takeaways
  • Git stores snapshots as content-addressed objects: blobs, trees, commits; branches are movable pointers.
  • Changes move from working directory → staging area → repository.
  • Merges preserve history (fast-forward or merge commit); rebase rewrites commits into a linear history — never rebase shared branches.
  • fetch downloads; pull = fetch + merge/rebase; push publishes.
  • Undo with restore, revert (safe for shared history), reset (soft/mixed/hard), and recover with reflog.
  • bisect, blame, log -S and cherry-pick are invaluable for debugging history.
Interview questions
QWhat is the difference between git merge and git rebase?easy

Both integrate changes from one branch into another. Merge creates a merge commit joining the two histories, preserving exactly what happened and never rewriting existing commits. Rebase re-applies your commits on top of the target branch, producing new commits and a linear history. Rebase is great for cleaning up local feature branches, but shouldn't be used on commits others already have, because it rewrites history.

QHow do you undo a commit that has already been pushed to main?easy

Use git revert on that commit: it creates a new commit applying the inverse change, so history isn't rewritten and collaborators aren't disrupted. Resetting and force-pushing a shared branch would rewrite history others depend on.