Git & GitHub

Spread the love
Git & GitHub β€” The Complete Learning Resource
Version Control Β· Beginner β†’ Interview-Ready

Master Git & GitHub, properly.

From “why version control” to rebasing, pull requests, branching strategies, and the interview questions that trip people up β€” one resource, followed start to finish.

main feature/login merge
17 chapters 90+ commands 20 interview Q&A Copy-ready examples
Jump to a chapter
01 β€” The problem

Why version control?

Before you learn Git’s commands, it helps to feel the pain it removes. Every developer who has named a file report_final_v2_ACTUALLY_final.doc already understands the problem.

Software changes constantly β€” and rarely by one person alone. Without a system to track those changes, you hit walls fast: you overwrite a teammate’s work, you can’t tell what changed or why, you break something and can’t get back to the version that worked, and “who touched this line and when” becomes a mystery. A version control system (VCS) is the tool that records every change to your code over time, so you can review it, undo it, branch off it, and collaborate on it safely.

What a VCS gives you

A complete history
Every change is recorded with who made it, when, and why. You can travel back to any past version instantly.
A safety net
Broke something? Roll back. Nothing is ever truly lost β€” you can experiment fearlessly.
Real collaboration
Many people work on the same project at once, and the VCS merges everyone’s changes together.
Branching
Work on a new feature in isolation without touching the stable version, then combine it when it’s ready.
Accountability
blame shows exactly which change introduced a line β€” invaluable for debugging and reviews.
Confidence to ship
A known-good history plus branching is the foundation for testing, releases, and automation.

Three generations of version control

Understanding how we got to Git makes its design click:

  • Local VCS β€” early tools tracked versions only on your own machine. Fine solo, useless for teams.
  • Centralized VCS (CVCS) β€” tools like Subversion (SVN) and CVS keep history on one central server. Everyone checks code out from it. Better for teams, but the server is a single point of failure, and you need a connection to do almost anything.
  • Distributed VCS (DVCS) β€” Git (and Mercurial) give every developer a full copy of the entire repository, history and all. You can commit, branch, and view history completely offline, and there’s no single point of failure. This is why Git won.
In one sentence Git is a distributed version control system that records the full history of your project on every machine, so anyone can work independently and merge their changes together reliably.
02 β€” The distinction

Git vs GitHub β€” the confusion, cleared

This is the single most common beginner mix-up, and it comes up in interviews constantly. They’re related but completely different things.

Git = the tool
A free, open-source version control system that runs on your computer. It tracks changes, manages branches, and needs no internet or account. Created by Linus Torvalds in 2005.
GitHub = the platform
A website that hosts Git repositories in the cloud and adds collaboration features on top β€” pull requests, issues, code review, CI/CD, and more. Owned by Microsoft.

Put simply: Git is the engine; GitHub is one of the garages you can park it in. You can use Git entirely on your own with no GitHub at all. And GitHub isn’t the only option β€” its main alternatives are GitLab and Bitbucket, which host Git repositories too and add their own features.

GitGitHub
What it isA version control toolA hosting & collaboration platform
RunsLocally on your machineIn the cloud (a website)
Needs internet?NoYes
Needs an account?NoYes
AddsCommits, branches, merges, historyPull requests, issues, Actions, wikis, teams
AlternativesMercurial, SVN (different model)GitLab, Bitbucket, Azure DevOps
The mental model You do your work with Git locally β€” making commits and branches. When you want to back it up, share it, or collaborate, you push it to GitHub. Others pull your changes, review them, and it all stays in sync.
03 β€” Architecture

How Git works: architecture & internals

Most Git confusion disappears the moment you understand its three areas and what a commit really is. This is the mental model that makes every command make sense.

The three areas

Git organizes your work into three “areas.” Files move between them as you work, and the two commands you’ll use most β€” git add and git commit β€” are simply how you move changes from one area to the next.

…and git push sends committed snapshots to a remote like GitHub Β· git pull brings theirs back

  • Working directory β€” the real folder of files on your disk that you edit.
  • Staging area (the index) β€” a preview of your next commit. You git add the specific changes you want to include, which lets you craft clean, focused commits instead of dumping everything at once.
  • Repository β€” the hidden .git directory where Git permanently stores your committed history. When you git commit, the staged snapshot is saved here forever.
Why staging exists The staging area feels like an extra step at first, but it’s a feature: it lets you review and split your work so each commit is one logical change. Fixed a bug and a typo? Stage and commit them separately.

What is a commit, really?

A crucial idea that surprises people: Git does not store diffs β€” it stores snapshots. Each commit is a complete snapshot of what all your tracked files looked like at that moment. (Under the hood Git is smart about not duplicating unchanged files, but conceptually, think snapshots, not deltas.)

Every commit is identified by a unique SHA-1 hash (a 40-character fingerprint like a1b2c3d…) computed from its contents. Change anything and the hash changes. Each commit also records its parent commit, which is how Git chains commits into a history you can walk backward through.

The object model

Internally, Git is a simple content-addressable database built from just a few object types:

blob
The contents of a single file. Just the data, no filename.
tree
A directory listing β€” maps filenames to blobs and other trees.
commit
A snapshot: points to one tree, plus author, message & parent commit(s).

So a commit points to a tree (your whole project’s folder structure), which points to blobs (file contents) and sub-trees. Everything is addressed by the hash of its content, which is what makes Git so fast and tamper-evident.

Refs and HEAD

Commit hashes are unwieldy, so Git uses friendly pointers called refs:

  • A branch (like main) is just a lightweight, movable pointer to a commit. That’s the whole secret β€” this is why branching in Git is instant and cheap.
  • HEAD is a pointer to where you are right now β€” usually the branch you currently have checked out. When you commit, HEAD’s branch moves forward to the new commit.
  • A tag is a fixed pointer to a specific commit, typically used to mark releases like v1.0.
The whole picture Your history is a graph of commits (a DAG β€” directed acyclic graph). Branches and HEAD are just pointers into that graph. Almost every Git command is, at heart, either creating commits or moving these pointers around.
04 β€” Vocabulary

Terminology & glossary

The words you’ll meet everywhere in Git. Learn these and the documentation β€” and the interviews β€” read easily.

Repository (repo)
A project tracked by Git β€” your files plus the entire .git history.
Commit
A saved snapshot of your changes, with a message and a unique hash.
Branch
A movable pointer to a commit β€” an independent line of work.
HEAD
A pointer to your current commit/branch β€” “you are here.”
Working tree
The actual files in your folder that you edit right now.
Staging area / Index
The set of changes queued for your next commit.
Remote
A version of your repo hosted elsewhere (e.g. on GitHub).
Origin
The default name Git gives to the remote you cloned from.
Clone
Download a full copy of a remote repository to your machine.
Fork
Your own copy of someone else’s repo on GitHub, to change freely.
Upstream
The original repo a fork was made from, or the remote branch you track.
Fetch
Download new commits from a remote without changing your files.
Pull
Fetch and merge remote changes into your current branch.
Push
Upload your local commits to a remote.
Merge
Combine the history of two branches together.
Rebase
Move your commits to start from a different base, for a cleaner history.
Stash
Temporarily shelve uncommitted changes to switch tasks.
Tag
A fixed label on a commit, usually marking a release.
SHA / hash
The unique fingerprint that identifies a commit.
Detached HEAD
When HEAD points at a commit directly, not a branch β€” look, don’t build here.
05 β€” Setup

Install & first-time setup

A five-minute setup you do once per machine. Getting your identity and SSH keys right now saves headaches later.

Install Git

  • Windows β€” download “Git for Windows” from git-scm.com; it includes Git Bash, a handy terminal.
  • macOS β€” run git --version to trigger the developer tools install, or use Homebrew: brew install git.
  • Linux β€” sudo apt install git (Debian/Ubuntu) or sudo dnf install git (Fedora).

Tell Git who you are

Every commit is stamped with a name and email. Set them once, globally:

one-time configuration
git config --global user.name "Your Name"
git config --global user.email "you@example.com"

# Make "main" the default branch name for new repos
git config --global init.defaultBranch main

# Set your preferred editor (e.g. VS Code)
git config --global core.editor "code --wait"

# Check everything
git config --list

Connect to GitHub with SSH

SSH keys let you push and pull without typing a password every time. Generate a key, then add the public half to GitHub (Settings β†’ SSH and GPG keys).

SSH key setup
# Generate a new key
ssh-keygen -t ed25519 -C "you@example.com"

# Copy the PUBLIC key, then paste it into GitHub settings
cat ~/.ssh/id_ed25519.pub

# Test the connection
ssh -T git@github.com
HTTPS alternativePrefer HTTPS? You can clone over https:// instead and authenticate with a Personal Access Token (PAT) or the GitHub CLI. SSH is just less typing day to day.
06 β€” Daily driving

The everyday workflow

Ninety percent of your Git life is one short loop: change files, stage them, commit them, push them. Master this and you’re productive.

The lifecycle of a file

Every file Git tracks moves through a few states. Knowing which state a file is in tells you what to do next:

Untracked→ git add → Staged→ git commit → Committed→ edit → Modified↺

Start a repo β€” two ways

create or clone
# A) Turn an existing folder into a repo
git init

# B) Copy an existing repo from GitHub
git clone git@github.com:user/project.git

The core loop

edit β†’ add β†’ commit β†’ push
git status                 # what's changed? (run this constantly)
git add index.html         # stage one file...
git add .                  # ...or everything that changed
git commit -m "Add contact form"   # save a snapshot
git push                   # send commits to the remote

Seeing what’s going on

inspect
git status                 # current state of working tree & staging
git diff                   # unstaged changes, line by line
git diff --staged          # what you're about to commit
git log --oneline --graph --all   # compact, visual history
git show HEAD              # details of the latest commit
Habit worth formingRun git status before and after almost everything. It’s free, it’s fast, and it stops most mistakes before they happen.
07 β€” Parallel work

Branching & merging

Branching is Git’s superpower. Because a branch is just a movable pointer to a commit, creating one is instant β€” and it changes how you work.

The idea: keep your stable code on main, and do every new feature or fix on its own branch. You can experiment freely; if it works, you merge it back; if it doesn’t, you throw the branch away and main was never touched.

create, switch, merge
# Create a branch and switch to it (modern syntax)
git switch -c feature/login
# (older equivalent: git checkout -b feature/login)

# ...do your work, add and commit as usual...

git switch main          # go back to main
git merge feature/login  # bring the feature in
git branch -d feature/login   # clean up the merged branch

Two kinds of merge

  • Fast-forward merge β€” if main hasn’t moved since you branched, Git simply slides main‘s pointer forward to your branch’s latest commit. No merge commit, perfectly linear history.
  • Three-way merge β€” if both branches have new commits, Git combines them and creates a new merge commit with two parents, tying the histories together.
Why branches are cheapOther version control systems copied entire folders to branch. Git just writes a new 40-character pointer. That’s why Git developers branch for even tiny tasks β€” it costs nothing.
branch management
git branch                 # list local branches
git branch -a              # include remote branches
git switch main          # switch branches
git branch -m old new       # rename a branch
git branch -D feature/x     # force-delete (even if unmerged)
08 β€” When histories collide

Merge conflicts, demystified

Conflicts scare beginners, but they’re just Git being honest: two branches changed the same lines, and Git won’t guess which one you meant. You decide.

When a merge can’t be done automatically, Git pauses and marks the clashing spot inside the file with conflict markers:

a conflict in greeting.js
<<<<<<< HEAD
const greeting = "Hello there!";   // your current branch's version
=======
const greeting = "Hi, welcome!";    // the incoming branch's version
>>>>>>> feature/login

How to resolve one, step by step

  1. Run git status to see which files conflict.
  2. Open each file and find the <<<<<<< markers.
  3. Edit the file to the version you actually want β€” keep one side, the other, or blend them β€” then delete all three marker lines.
  4. Stage the resolved file with git add.
  5. Complete the merge with git commit (Git pre-fills a message).
resolving
git status                 # lists "both modified" files
# ...edit files, remove markers, keep what you want...
git add greeting.js        # mark it resolved
git commit                 # finish the merge

# Changed your mind mid-merge? Abort and start over:
git merge --abort
Fewer conflictsPull often, keep branches short-lived, and make small focused commits. Most conflict pain comes from letting a branch drift far from main for weeks.
09 β€” Advanced history

Rebasing & rewriting history

This is where Git gets powerful β€” and where you can hurt yourself if you skip the one golden rule. Take it slow; it’s worth it and it’s a favorite interview topic.

Merge vs rebase

Both integrate changes from one branch into another; they differ in the history they leave behind.

  • Merge keeps history exactly as it happened and adds a merge commit. Honest and safe, but can get tangled with many small merges.
  • Rebase re-plays your branch’s commits on top of another branch, as if you’d started from its latest commit. Result: a clean, linear history β€” but the commits are rewritten (they get new hashes).
rebase your feature onto latest main
git switch feature/login
git rebase main        # replay my commits on top of main
# resolve any conflicts, then: git rebase --continue
The golden rule of rebasingNever rebase commits that you’ve already pushed and others may have based work on. Rewriting shared history forces painful fixes on everyone. Rule of thumb: rebase your own local work; merge anything public.

Interactive rebase β€” polish your commits

Interactive rebase lets you rewrite a series of your own commits before sharing them β€” squash several into one, reword messages, reorder, or drop them entirely.

tidy the last 3 commits
git rebase -i HEAD~3

# An editor opens; change "pick" to:
#   squash (s) β€” fold this commit into the one above
#   reword (r) β€” keep the commit, edit its message
#   drop   (d) β€” delete this commit entirely
#   edit / reorder lines to reorder commits

Cherry-pick & amend

surgical tools
# Copy one specific commit onto your current branch
git cherry-pick a1b2c3d

# Fix the most recent commit (message or forgotten file)
git add forgotten-file.js
git commit --amend
reflog: your safety netThink you lost commits after a rebase or reset? You almost certainly didn’t. git reflog records everywhere HEAD has been, so you can find the old commit’s hash and recover it. Git rarely deletes anything for ~30 days.
10 β€” The “oh no” reference

Undoing mistakes

Everyone makes them. This is the section you’ll bookmark and return to. The key skill is knowing which undo to reach for.

Before you’ve committed

working tree & staging
git restore file.js          # discard unstaged edits to a file
git restore --staged file.js # unstage (keep the edits)
git restore .                # discard ALL unstaged changes (careful!)
git clean -fd              # delete untracked files & folders

Fixing commits

amend, reset, revert
# Fix the LAST commit's message or contents
git commit --amend

# Undo last commit, KEEP changes staged
git reset --soft HEAD~1

# Undo last commit, KEEP changes but unstage them (default)
git reset HEAD~1

# Undo last commit and THROW AWAY the changes (dangerous)
git reset --hard HEAD~1

# Safely undo a commit by making a NEW opposite commit
# (the right choice for shared/pushed history)
git revert a1b2c3d

reset vs revert β€” the interview classic

git resetgit revert
What it doesMoves the branch pointer back, rewriting historyAdds a new commit that undoes an old one
HistoryRewritten β€” old commits disappear from the branchPreserved β€” the undo is part of history
Safe on shared branches?No β€” never on pushed historyYes β€” designed for it
Use whenCleaning up local, unpushed workUndoing something already public
Lost something?Run git reflog, find the hash of the commit you want back, and git reset --hard <hash> (or git checkout <hash>) to recover it. This has saved countless careers.
11 β€” Working together

Remotes & collaboration

A remote is just another copy of your repo living somewhere else β€” usually GitHub. Three verbs keep you in sync: fetch, pull, and push.

git fetch
Downloads new commits from the remote but does not change your files. A safe “what’s new?” look.
git pull
fetch + merge in one step β€” grabs remote changes and integrates them into your branch.
git push
Uploads your local commits to the remote so others can see them.
managing remotes
git remote -v                          # list remotes and their URLs
git remote add origin git@github.com:you/repo.git
git push -u origin main              # push & set upstream (first time)
git fetch origin                       # see remote changes safely
git pull                               # fetch + merge into current branch
fetch, then mergeOn a shared branch, many teams prefer git fetch followed by reviewing changes, rather than a blind git pull. It’s the same result with a moment to look before you leap. Add git pull --rebase to keep history linear.

The forking workflow (open source)

You usually can’t push directly to someone else’s repo. Instead you fork it (make your own copy on GitHub), clone your fork, push changes to it, and open a pull request back to the original. Keep your fork current by adding the original as an upstream remote:

keep a fork in sync
git remote add upstream git@github.com:original/repo.git
git fetch upstream
git switch main
git merge upstream/main      # pull the original's latest into your fork
git push origin main
12 β€” Code review

Pull requests & code review

The pull request (PR) is the heart of collaboration on GitHub. It’s not a Git feature β€” it’s a GitHub one β€” and it’s how teams review and discuss changes before they land.

A pull request is a proposal: “here are the commits on my branch β€” please review them and merge them into main.” It opens a dedicated page where teammates can read the diff, comment on specific lines, request changes, approve, and watch automated checks (tests, linters) run before anything merges.

The PR lifecycle

  1. Create a branch, commit your work, and push it to GitHub.
  2. Open a pull request from your branch into main (GitHub usually shows a prompt).
  3. Write a clear title and description β€” what changed and why. Link any related issue (e.g. “Closes #42”).
  4. Reviewers comment, request changes, or approve. You push follow-up commits to address feedback β€” the PR updates automatically.
  5. Once approved and checks pass, someone merges it. Delete the branch.

Three ways to merge a PR

Merge typeWhat it doesBest for
Merge commitKeeps every commit and adds a merge commitPreserving full, honest history
Squash & mergeCombines all PR commits into one clean commitA tidy, one-commit-per-feature main branch
Rebase & mergeReplays commits onto main with no merge commitA strictly linear history
What makes a good PRKeep it small and focused, write a description that explains the “why,” and self-review the diff before requesting others. A 200-line PR gets a real review; a 2,000-line one gets a rubber stamp.

Do it from the terminal (GitHub CLI)

gh β€” GitHub’s official CLI
gh pr create --title "Add login form" --body "Closes #42"
gh pr status          # see your PRs
gh pr checkout 123     # check out someone's PR to test it
gh pr merge 123 --squash
13 β€” Planning & tracking

Issues & project management

Issues are how GitHub turns a code repository into a place to plan work, track bugs, and have conversations β€” no separate tool required.

An issue is a tracked item: a bug report, a feature request, a question, or a task. Each has a title, a description, a comment thread, and a set of tools to organize it:

Labels
Colored tags like bug, enhancement, or good first issue to categorize and filter.
Assignees
The person responsible for the issue, so it’s clear who’s on it.
Milestones
Group issues into a target release or sprint with a due date.
Projects
A kanban-style board (To do / In progress / Done) built from issues and PRs.

Link issues to code

The magic connection: mention an issue number in a commit or PR and GitHub links them automatically. Use a closing keyword and merging the PR will close the issue for you.

closing keywords in a commit or PR
git commit -m "Fix null crash on empty cart"
# In the PR description, write:
#   Closes #42     (also: Fixes #42, Resolves #42)
# β†’ merging the PR auto-closes issue #42
Beyond issuesGitHub also offers Discussions (open-ended Q&A, unlike task-focused issues), Wikis for documentation, Releases to package versioned downloads from tags, and Actions for CI/CD automation β€” all in the same repo.
14 β€” How teams organize

Branching strategies

Once a team shares a repo, they need an agreed way to use branches. There’s no single “right” answer β€” the best strategy depends on how you ship.

GitHub Flow

main + short-lived feature branches + PR + deploy

The simplest modern approach: main is always deployable. For any change, branch off main, open a pull request, get it reviewed, and merge. Deploy continuously. That’s it.

Best for: web apps and teams practicing continuous delivery. The default for most projects today.

Git Flow

main + develop + feature/* + release/* + hotfix/*

A structured model with long-lived main (production) and develop (integration) branches, plus dedicated feature, release, and hotfix branches. Powerful but heavier, with more ceremony around each release.

Best for: versioned software with scheduled releases and multiple versions in the wild. Often overkill for continuous web deployment.

Trunk-Based Development

everyone commits to main, in tiny increments, behind feature flags

Developers integrate into a single main (“the trunk”) at least daily, using very short-lived branches and feature flags to hide unfinished work. Minimizes merge pain and maximizes integration.

Best for: mature teams with strong automated testing and a culture of small, frequent commits. Common at large tech companies.
ChoosingStart with GitHub Flow β€” it’s simple and fits most teams. Reach for Git Flow only if you genuinely ship versioned releases, and move toward trunk-based development as your test automation matures.
15 β€” Reference

Command cheat sheet

The commands worth keeping within reach, grouped by what you’re trying to do. Bookmark this section.

Setup & config
git config –global user.name “Name”
Set the name attached to your commits.
git config –list
Show all current configuration.
git init
Start a new repository in the current folder.
git clone <url>
Copy a remote repository to your machine.
Everyday snapshotting
git status
Show what’s changed, staged, and untracked.
git add <file> Β· git add .
Stage a file, or everything, for the next commit.
git commit -m “message”
Save a snapshot of staged changes.
git commit –amend
Modify the most recent commit.
git diff Β· git diff –staged
See unstaged, or staged, line-by-line changes.
Branching & merging
git branch
List branches.
git switch -c <name>
Create and switch to a new branch.
git switch <name>
Switch to an existing branch.
git merge <name>
Merge a branch into your current one.
git branch -d <name>
Delete a merged branch.
Remotes & syncing
git remote -v
List remote repositories.
git fetch
Download remote changes without merging.
git pull
Fetch and merge remote changes.
git push Β· git push -u origin <branch>
Upload commits; -u sets the upstream on first push.
Inspecting history
git log –oneline –graph –all
Compact, visual commit history.
git show <commit>
Details and diff of one commit.
git blame <file>
Show who last changed each line.
git reflog
History of everywhere HEAD has been (recovery).
Undoing & rewriting
git restore <file>
Discard unstaged changes to a file.
git restore –staged <file>
Unstage a file (keep the edits).
git reset –soft/–mixed/–hard HEAD~1
Undo commits, keeping / unstaging / discarding changes.
git revert <commit>
Safely undo a commit with a new commit.
git rebase -i HEAD~n
Interactively squash, reword, or reorder commits.
git cherry-pick <commit>
Apply one specific commit here.
Stashing
git stash
Shelve uncommitted changes and clean your tree.
git stash pop
Reapply the most recent stash and remove it.
git stash list
See all shelved stashes.
16 β€” In practice

Real-world scenarios

The situations you’ll actually face, and exactly what to type. From your first push to untangling a mistake under pressure.

Beginner

Start a project and push it to GitHub

Create the repo on GitHub (empty), then connect your local folder to it.

first push
git init
git add .
git commit -m "Initial commit"
git remote add origin git@github.com:you/project.git
git push -u origin main
Beginner

Work on a feature without breaking main

Branch, build, merge back. Your stable code is never at risk.

feature branch
git switch -c feature/search
# ...work, add, commit...
git push -u origin feature/search
# open a Pull Request on GitHub, get it reviewed & merged
Intermediate

Contribute to an open-source project

Fork it, clone your fork, branch, push, and open a PR to the original.

fork & PR flow
# after clicking "Fork" on GitHub:
git clone git@github.com:you/their-project.git
git switch -c fix/typo-in-readme
# ...make the change, commit...
git push -u origin fix/typo-in-readme
# open a PR from your fork β†’ the original repo
Intermediate

You committed to the wrong branch

Move the last commit to where it belongs.

rescue a misplaced commit
# you're on main but meant to commit to a feature branch
git switch -c feature/right-place   # bring the commit with you
git switch main
git reset --hard HEAD~1            # remove it from main
Advanced

Undo a bad change that’s already public

Never rewrite shared history β€” revert instead, creating a clean, honest undo.

safe public undo
git revert a1b2c3d    # makes a new commit that undoes a1b2c3d
git push
17 β€” Interview prep

Interview questions

The Git & GitHub questions that come up again and again, with concise answers you can say out loud. Tap any question to reveal the answer.

What’s the difference between Git and GitHub?
Git is a distributed version control tool that runs locally on your machine and tracks changes. GitHub is a cloud platform that hosts Git repositories and adds collaboration features like pull requests, issues, and CI/CD. Git is the engine; GitHub is a host for it (alternatives include GitLab and Bitbucket).
Explain the three areas / states in Git.
The working directory (your actual files), the staging area / index (changes queued for the next commit, put there with git add), and the repository (committed history in .git, written with git commit). Staging lets you craft focused commits.
Does Git store diffs or snapshots?
Conceptually, snapshots. Each commit captures the complete state of tracked files (Git avoids duplicating unchanged content under the hood, but the model is snapshot-based, not delta-based like some older systems).
What is HEAD? What’s a detached HEAD?
HEAD is a pointer to your current location β€” usually the branch you have checked out. A detached HEAD is when HEAD points directly at a specific commit rather than a branch; commits made there aren’t on any branch and can be lost unless you create a branch to keep them.
Merge vs rebase β€” what’s the difference?
Merge combines two branches and creates a merge commit, preserving history exactly as it happened. Rebase replays your commits on top of another branch for a clean, linear history but rewrites those commits (new hashes). Golden rule: never rebase commits you’ve already shared publicly.
git fetch vs git pull?
fetch downloads remote changes but doesn’t touch your working files. pull is fetch + merge β€” it downloads and integrates in one step. Fetch is the safer “look first” option.
git reset vs git revert?
reset moves the branch pointer back and rewrites history (use only on local, unpushed work). revert creates a new commit that undoes a previous one, preserving history β€” the safe choice for shared branches.
What do soft, mixed, and hard reset do?
--soft moves HEAD but keeps changes staged. --mixed (default) keeps changes but unstages them. --hard discards the changes entirely. Hard is the destructive one.
How do you undo the last commit?
If unpushed and you want to keep the work: git reset --soft HEAD~1. To just fix it: git commit --amend. If already pushed: git revert <hash> to add a safe undo commit.
What is a fast-forward merge?
When the target branch hasn’t diverged, Git simply advances its pointer to the source branch’s latest commit β€” no merge commit needed. It only happens when there’s a straight, linear path between the two.
What is git cherry-pick?
It applies the changes from one specific commit onto your current branch, creating a new commit. Useful for grabbing a single fix from another branch without merging everything.
What does git stash do?
It shelves your uncommitted changes and gives you a clean working tree, so you can switch tasks or branches. git stash pop brings them back. Handy when you’re mid-change and need to jump to something urgent.
How do you resolve a merge conflict?
Git marks the clashing lines with <<<<<<<, =======, >>>>>>>. Open the file, edit it to the version you want, delete the markers, then git add the file and git commit to complete the merge.
Forking vs cloning?
Cloning copies a repo to your local machine. Forking creates your own server-side copy on GitHub (typically of someone else’s repo) that you can push to freely and later propose changes back via a pull request.
What is “origin”?
It’s the default name Git assigns to the remote repository you cloned from. It’s just a convention/alias for a URL β€” you can rename it or add other remotes (like upstream).
What is a pull request?
A GitHub feature (not a Git command) that proposes merging one branch into another, opening a page for review, discussion, line comments, and automated checks before the code is merged.
What goes in a .gitignore file?
Patterns for files Git should not track β€” build artifacts, dependencies (node_modules/), logs, environment/secret files, and OS/editor junk. It keeps the repo clean and prevents accidentally committing secrets.
How would you recover a “lost” commit?
Use git reflog to find the commit’s hash in HEAD’s history, then git reset --hard <hash> or git checkout <hash>. Git keeps unreferenced commits for about 30 days, so they’re rarely truly gone.
What is git squash and why use it?
Squashing combines multiple commits into one, usually via interactive rebase (git rebase -i) or “Squash & merge” on a PR. It produces a cleaner history β€” one tidy commit per feature instead of many “wip” commits.
Explain a branching strategy you know.
GitHub Flow: main is always deployable; every change goes on a short-lived branch, through a reviewed pull request, then merges and deploys. Simple and continuous. Alternatives include the more structured Git Flow and integration-heavy trunk-based development.

This is a sensitive-free technical topic β€” but if you’re preparing for a real interview, the best follow-up is to actually run each command on a throwaway repo. Muscle memory beats memorization.