DevOps, CI/CD & Containers
Git Fundamentals: Commits, the Working Tree, Remotes and Undoing Changes
Beginner9 min readUpdated
Git is easier to use well once you understand the model underneath the commands: a graph of immutable snapshots, three places a change can live, and branches that are just movable pointers. This guide builds that model, then covers the daily workflow — clone, stage, commit, fetch, pull, push — and the different ways to undo things, so you can recover from mistakes without fear.
What you will learn
- Explain how Git stores history as a graph of content-addressed snapshots
- Move changes between the working tree, the index and the repository deliberately
- Synchronise with a remote using fetch, pull and push and read what they report
- Undo mistakes with restore, reset, revert and the reflog, choosing the safe option each time
- Configure Git, ignore files correctly and write commit messages that help future readers
Most Git tutorials teach a sequence of commands to memorise. That works until something goes wrong, and with Git something always eventually goes wrong: a commit on the wrong branch, a pull that produced a merge you did not expect, a reset that seemed to eat an afternoon's work. The way out is to understand the small number of ideas the commands are built on. Git's model is simpler than its command-line surface suggests, and once you can picture what a command does to the graph of commits, the reference manual becomes readable and the panic goes away. This guide targets Git 2.4x and uses the modern switch and restore commands where older material used checkout for everything.
What Git stores
A Git repository is a database of four kinds of object, each identified by the SHA-1 (or, in newer repositories, SHA-256) hash of its content:
- A blob is the content of one file, with no name and no metadata.
- A tree is a directory listing: names, permissions and the hashes of the blobs and sub-trees it contains.
- A commit points at one tree (the complete snapshot of the project at that moment), at zero or more parent commits, and carries the author, committer, timestamps and message.
- A tag object attaches a name, a message and optionally a signature to a commit.
Two consequences follow. First, a commit is a snapshot, not a diff: Git stores the whole tree each time, deduplicated by hash, so unchanged files cost nothing and any commit can be checked out without replaying history. Diffs are computed on demand. Second, everything is immutable and content-addressed: change a single byte anywhere in history and every hash above it changes, which is why "rewriting history" means creating new commits, and why a hash is a trustworthy identifier for exactly one state of the code.
Commits with their parent links form a directed acyclic graph. A branch is nothing more than a file containing the hash of a commit — a movable pointer that advances when you commit on it. HEAD is a pointer to the branch you currently have checked out. Creating a branch is writing 41 bytes to a file, which is why it is instantaneous and why Git users branch far more freely than users of older systems.
The three areas
A change moves through three places, and most confusion about Git comes from not knowing which one a command affects.
| Area | What it is | Commands that write to it |
|---|---|---|
| Working tree | The files on disk you edit | editor, git restore, git switch, git merge |
| Index (staging area) | The proposed next commit, stored in .git/index | git add, git rm, git restore --staged, git reset |
| Repository | The object database and refs under .git | git commit, git fetch, git merge, git reset |
The index is the piece newcomers find odd. Its purpose is to let you build a commit deliberately: edit five files, stage the three that belong together, commit, then stage the other two as a separate commit. git add -p takes this further by staging individual hunks within a file. git status always reports both what is staged and what is modified but unstaged; git diff shows working tree versus index, and git diff --staged shows index versus the last commit.
git status # what is staged, modified, untracked
git add src/Order.java # stage one file
git add -p # stage hunks interactively
git diff --staged # review exactly what the commit will contain
git commit -m "Reject orders with a negative quantity"
The daily workflow
Starting from an existing project:
git clone [email protected]:acme/shop.git
cd shop
git switch -c fix-negative-quantity # create and switch to a branch
# ... edit, test ...
git add -A
git commit
git push -u origin fix-negative-quantity # -u sets the upstream so later pushes need no arguments
clone copies the entire repository — all history, all branches — and sets up a remote named origin pointing at where it came from. For each branch on the remote you get a remote-tracking branch, origin/main, origin/release-2.4 and so on. These are read-only bookmarks of what the remote looked like the last time you talked to it; you never commit to them directly.
git fetch updates the remote-tracking branches and downloads any new objects, changing nothing about your own branches. git pull is fetch followed by integrating origin/<branch> into your current branch, by merge or rebase depending on configuration. Because a pull can produce a merge commit you did not intend, many developers set git config --global pull.rebase true so that local commits are replayed on top of the fetched ones and history stays linear; the branching workflows guide discusses the trade-off.
git push sends your commits to the remote and moves its branch. It is refused if the remote branch has commits you do not have — a non-fast-forward — which protects you from overwriting someone else's work. The correct response is to fetch and integrate, then push again; --force should be reserved for branches only you work on, and even then prefer --force-with-lease, which fails if the remote changed since your last fetch.
Reading history
git log --oneline --graph --decorate -20 # compact graph with branch and tag labels
git log -p -- src/Order.java # every change to one file, with diffs
git log --author=alice --since=2.weeks
git show a1b2c3d # one commit: metadata plus diff
git blame src/Order.java # which commit last touched each line
git diff main...feature # what feature adds relative to the merge base
The three-dot form in the last line is worth learning: A..B means "commits reachable from B but not A", while A...B in git diff means "changes on B since it diverged from A", which is what you want when reviewing a branch.
Undoing things safely
Git offers several ways to undo, and choosing correctly depends on two questions: has the change been committed, and has it been shared?
Discard uncommitted edits in the working tree. git restore <file> replaces the file with the index version. The change is gone for good — it was never committed — so check git diff first.
Unstage without losing edits. git restore --staged <file> copies the last commit's version back into the index and leaves the working tree alone.
Fix the last commit. git commit --amend replaces the tip commit with a new one containing the current index (and a possibly edited message). Fine before pushing; after pushing it rewrites shared history.
Move a branch backwards. git reset moves the current branch pointer to another commit. With --soft the index and working tree keep the later changes (useful for squashing the last few commits into one); with the default --mixed the index is reset but files are untouched; with --hard everything matches the target commit and uncommitted work is destroyed.
git reset --soft HEAD~3 # collapse the last three commits into staged changes
git commit -m "Implement discount codes"
Undo a shared commit. git revert <hash> creates a new commit that applies the inverse change. History is preserved, nothing anyone fetched becomes invalid, and it is the only correct way to undo something on main after it has been pushed.
Recover "lost" commits. Every time HEAD moves, Git records where it was in the reflog. After a bad reset or a deleted branch, git reflog lists the recent positions and git reset --hard HEAD@{2} or git switch -c rescued <hash> brings the commits back. Unreachable objects are kept for at least 30 days by default, so almost anything committed is recoverable within that window.
Stashing
git stash saves the working tree and index changes onto a stack and cleans the working tree, so you can switch branches to fix something urgent and come back. git stash pop restores the most recent stash and drops it; git stash list shows what is parked; git stash push -m "wip: pricing" -- src/pricing stashes only some paths with a label. Stashes are commits too, and a popped stash that conflicts leaves both the stash and the conflict markers in place, so nothing is lost.
Ignoring files and configuring Git
A .gitignore file lists patterns for files Git should not track — build output, dependency directories, editor settings, secrets. Patterns are matched relative to the file's directory; a leading / anchors to that directory, a trailing / matches only directories, and ! negates.
# Build output
/target/
/build/
node_modules/
# IDE and OS noise
.idea/
*.iml
.vscode/
.DS_Store
# Never commit secrets
.env
*.pem
Two things trip people up. .gitignore does not affect files that are already tracked — you must git rm --cached them first. And an ignore entry is not a security control: a file committed once is in history until history is rewritten, and any secret it contained must be rotated.
Configuration lives at three levels — system, global (~/.gitconfig) and repository (.git/config) — each overriding the previous. The settings worth applying on every new machine:
git config --global user.name "Alice Martin"
git config --global user.email [email protected]
git config --global init.defaultBranch main
git config --global pull.rebase true
git config --global push.autoSetupRemote true # first push needs no -u
git config --global core.autocrlf input # on Linux/macOS; "true" on Windows
git config --global rerere.enabled true # remember how you resolved conflicts
Tags
A tag marks a commit as significant, usually a release. Lightweight tags (git tag v2.4.0) are bare pointers; annotated tags (git tag -a v2.4.0 -m "Release 2.4.0") are objects with a tagger, date and message and can be signed. Use annotated tags for releases: they carry provenance and git describe prefers them. Tags are not pushed by default — git push origin v2.4.0 or git push --tags — and unlike branches they are meant to be permanent; moving a tag that others have fetched causes lasting confusion.
Writing commits worth reading
A commit is a unit of change and a message to the person who reads the history a year later, often while bisecting a bug. Keep each commit to one logical change, so that it can be reverted or cherry-picked on its own. Write the subject line in the imperative ("Add retry to payment client"), under about 50 characters, and put the why in the body: what problem existed, why this approach, what alternatives were rejected. The diff already shows what changed; the message exists to explain what the diff cannot.
git bisect is the payoff for small, well-described commits. Given a known-good and a known-bad commit, it checks out the midpoint, you (or a script) report good or bad, and it homes in on the offending commit in logarithmic steps. It is only useful when every commit builds and does one thing.
Common mistakes
- Committing generated files and dependencies.
target/,node_modules/and.classfiles bloat the repository and cause endless conflicts. Ignore them from the first commit. git add .from the wrong directory. It stages everything below the current directory, including files you did not mean to include. Reviewgit statusbefore committing.- Force-pushing a shared branch. Colleagues' pushes are rejected, their local branches diverge and someone eventually re-pushes the old history. Use
--force-with-leaseon personal branches only. - Pulling with uncommitted changes. A merge or rebase over dirty files produces confusing conflicts. Commit or stash first.
- Treating
reset --hardas the answer to everything. It destroys uncommitted work; stash instead, and use the reflog to return to commits. - Committing secrets "temporarily". They remain in history. Rotate the credential immediately and use
git filter-repoif the history must be purged. - Giant commits. A 60-file commit titled "changes" is impossible to review, revert or bisect. Stage in logical pieces.
Key takeaways
- Git stores immutable, content-addressed snapshots linked into a graph; branches are movable pointers into that graph and
HEADmarks where you are. - Changes live in the working tree, the index or the repository;
status,diffanddiff --stagedtell you which, andaddbuilds the next commit deliberately. fetchupdates remote-tracking branches without touching your work;pullalso integrates;pushrefuses to overwrite commits you have not seen.- Undo uncommitted work with
restore, reshape local commits withresetandamend, undo shared commits withrevert, and recover from almost anything withreflog. - Keep generated files out with
.gitignore, setpull.rebaseand line-ending options globally, and use annotated tags for releases. - Small, single-purpose commits with messages that explain the reason are what make history, bisect and review useful later.
Sources and further reading
Frequently asked questions
- What is the difference between git fetch and git pull?
- fetch downloads new commits and updates the remote-tracking branches (such as origin/main) without touching your branch or working tree. pull is fetch followed by merge or rebase into your current branch. Fetch first when you want to inspect what changed before integrating it; pull when you are ready to integrate straight away.
- I committed to the wrong branch. How do I fix it?
- If you have not pushed, note the commit hash from git log, switch to the correct branch and run git cherry-pick with that hash, then go back to the wrong branch and run git reset --hard HEAD~1 to drop the commit there. If you have already pushed the wrong branch, prefer git revert so that you do not rewrite history others may have fetched.
- Is git reset --hard dangerous?
- It discards uncommitted changes in the working tree and index permanently — those were never in a commit, so nothing can recover them. Commits that reset moves away from are not deleted immediately; git reflog still lists them for at least 30 days by default and you can reset back to them. Before a hard reset, run git status and stash anything you might want.
- Why does Git say 'detached HEAD'?
- HEAD normally points at a branch name, and committing moves the branch. If you check out a specific commit or tag, HEAD points directly at that commit instead. Commits made in this state belong to no branch and will be garbage-collected eventually unless you run git switch -c some-branch to create one at that point.