Appearance
13.11.1 — Git from Zero: The Three Areas and Your First Commits
You are changing a file called cart.ts. It worked yesterday. Today it is broken, and you cannot remember what you changed.
Without version control, people save copies: cart.ts, cart-old.ts, cart-final.ts, cart-final-REAL.ts. After a week nobody knows which one is current. After a month the folder is a graveyard.
Git fixes this. It is a program that remembers every saved version of your project, who saved it, when, and why, and it lets you go back to any of them.
Linus Torvalds started it in April 2005. The Linux kernel had thousands of contributors, and the paid tool they used had just withdrawn its free licence. Within about two weeks, Git was managing the kernel's own history. Today almost every software project in the world uses Git, and almost every job description for a developer lists it. This page teaches you the first half of it from nothing. The next pages build on it.
1. Four words you need first
You will see these words on every line of Git output, so here they are in plain English.
A repository is a project folder that Git is watching. It holds your files and the full history of every change. People say "repo" for short.
A commit is one saved version of the whole project. Think of it as a save point in a video game. Each commit has a message that says what changed and why.
The working directory (also called the working tree) is the normal folder you see on your disk. It holds the files you open in your editor.
HEAD is Git's name for "the commit I am standing on right now". It starts to matter on the next page. For now, read it as "the latest save".
2. Install Git and tell it who you are
Open a terminal (the black window where you type commands) and ask for the version:
text
$ git --version
git version 2.43.0If you see a version number, you have Git. If not, install it from git-scm.com. On macOS, typing git the first time offers to install it. On Ubuntu it is sudo apt install git.
Every commit records who made it. Git cannot guess your name, so you tell it once:
bash
git config --global user.name "Ana Ruiz" # (1)
git config --global user.email "ana@example.com" # (2)
git config --global init.defaultBranch main # (3)- This is the name that appears next to every commit you make.
- This is your email. Use the same one as your GitHub account if you will use GitHub, because that is how GitHub links commits to your profile.
- This sets the name of the first branch in every new repository to
main. Older Git versions called itmaster. You will learn what a branch is on the next page.
The word --global means "for every project on this computer". Git stores these settings in a plain text file called ~/.gitconfig in your home folder. You can look at what you have set:
text
$ git config --global --list
user.name=Ana Ruiz
user.email=ana@example.com
init.defaultbranch=mainIf you skip this step, your first commit stops with an error that says Author identity unknown. Now you know what it means and how to fix it.
3. Make a repository: git init
We will build a tiny shop project, one step at a time, and watch what Git does.
text
$ mkdir shop && cd shop
$ git init
Initialized empty Git repository in /home/ana/shop/.git/Two things happened. mkdir shop made a new empty folder, and cd shop moved you into it. Then git init created one hidden folder inside it, called .git.
text
$ ls -a
. .. .gitThat .git folder is the entire repository. Every saved version, every message, every setting for this project lives inside it. Your normal files are only the current copy.
This has a useful consequence. If you delete the .git folder, the folder turns back into an ordinary folder and the history is gone. If you copy the whole project folder to a USB stick, the history comes with it. Chapter 13.11.5 opens .git and shows what is inside.
Now ask Git what it sees:
text
$ git status
On branch main
No commits yet
nothing to commit (create/copy files and use "git add" to track)git status is the command you will type most. It answers one question: what is going on right now? Here it says three things. You are on a branch called main. There are no commits yet. There is nothing to save.
Get in the habit of typing git status before and after almost every other command. It costs nothing and it prevents most mistakes.
4. The three areas
Before you save anything, you need one picture in your head. Almost every confusing thing about Git goes away once you know it.
When you work with Git, your files live in three places, not one.
The working directory is the real folder. When you open cart.ts in your editor and type, you are changing a file here. Git does not save anything yet.
The staging area is a waiting room. You put changes there when you want them in the next save. Some people call it the index. It is a list, kept inside .git, that says "these exact changes go into my next commit".
The repository is the permanent record: all the commits so far. Once a change is committed here, Git keeps it.
You might ask why the waiting room exists. Why not save every change automatically?
Here is the reason. Imagine you spend the morning fixing a bug in the cart, and while you are in the file you also tidy up some variable names. Those are two different pieces of work. If you save them as one commit, a reader later sees a blob of unrelated changes. If the bug fix turns out to be wrong and you need to undo it, the renaming goes with it.
The staging area lets you say: "Put the bug fix in this save. Put the renaming in the next one." You choose, piece by piece, what each commit contains. A history made of small, clear commits is something your team can actually read. This is the single biggest difference between Git and the "save everything" tools that came before it.
5. Your first commit
Let us make a file and watch it move through the three areas.
text
$ echo "# Shop" > README.md
$ git status
On branch main
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
README.md
nothing added to commit but untracked files present (use "git add" to track)The first command created a file called README.md with one line in it. Git noticed the new file and put it under Untracked files. "Untracked" means Git can see the file in your folder but has never been told to keep it. Git will not save a file until you say so.
Step one: stage it.
text
$ git add README.md
$ git status
On branch main
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: README.mdThe heading changed to Changes to be committed. The file is now in the waiting room. Nothing is saved yet. If your laptop died now, the history would still be empty.
Step two: commit it.
text
$ git commit -m "Add README"
[main (root-commit) 81dcd49] Add README
1 file changed, 1 insertion(+)
create mode 100644 README.mdRead the output from left to right.
mainis the branch you saved onto.(root-commit)means this is the very first commit in the repository. Later commits do not show this.81dcd49is the start of the commit's id. More on that in a moment.Add READMEis your message. The-mflag lets you write it on the same line. Without-m, Git opens a text editor and waits for you to type one.- The last two lines are a summary: one file changed, one line added.
Now look at the history:
text
$ git log
commit 81dcd49fd0b4d93c98e590ef98893e2522c2321a
Author: Ana Ruiz <ana@example.com>
Date: Wed Oct 28 12:14:48 2026 +0000
Add READMEA commit has four parts: an id, an author, a date and a message.
The id is the long string of letters and numbers: 81dcd49fd0b4d93c98e590ef98893e2522c2321a. It is 40 characters long. Git works it out from the contents of the commit, so it works like a fingerprint: the same content always gives the same id, and no two different commits share one. Nobody wants to type 40 characters, so Git lets you use just the first 7 or so (81dcd49) as long as they are not ambiguous. That is why the short form appears in the output above. Chapter 13.11.5 explains exactly how the fingerprint is made.
6. The loop you will repeat for the rest of your career
Let us add real code.
text
$ cat cart.ts
export function total(prices: number[]): number {
return prices.reduce((a, b) => a + b, 0);
}
$ git status -s
?? cart.tsgit status -s is the short form. The two question marks ?? mean "untracked". Short form is handy once you can read it. Here is the whole code:
| Code | Meaning |
|---|---|
?? | Untracked: Git has never seen this file |
A | Added: staged as a new file |
M | Modified in the working directory, not staged |
M | Modified and staged |
MM | Modified, staged, and then modified again |
D | Deleted and staged |
R | Renamed and staged |
The first letter is the staging area. The second letter is the working directory. A space means "nothing there".
Save it:
text
$ git add cart.ts
$ git commit -m "Add cart total"
[main a6be824] Add cart total
1 file changed, 3 insertions(+)
create mode 100644 cart.ts
$ git log --oneline
a6be824 Add cart total
81dcd49 Add READMEgit log --oneline shows one line per commit: the short id and the message. The newest commit is at the top.
Here is that history drawn as Git sees it. Each commit remembers the one before it, so the history is a chain.
main sits on the newest commit, and HEAD says which label you are standing on.The arrows point backward, from each commit to its parent, the commit it was made after. main is a label on the newest commit, and HEAD points at main. You will see exactly how those labels work on the next page.
Now you know the whole loop. Edit, stage, commit. Everything else in Git is a variation on it. It is the same journey every file takes, and here it is as a diagram.
git status tells you which. Two commands move a file forward, and your own editor moves it back to the start of the loop.Every file in your project is in one of these four states. git status shows you which. An editor moves a file from "Committed" to "Modified" the moment you save a change. You move it forward with git add and then git commit. After the commit, the file is "Committed" again and the loop starts over.
7. Seeing what you changed: git diff
A diff is a list of the lines that changed between two versions of a file. Let us add a tax helper to cart.ts and look.
text
$ git status
On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: cart.ts
no changes added to commit (use "git add" and/or "git commit -a")This time the heading is Changes not staged for commit. The file is already tracked, and it has been edited, but it is not in the waiting room yet. Git even tells you the two commands you might want next: git add to stage it, or git restore to throw the edit away.
text
$ git diff
diff --git a/cart.ts b/cart.ts
index 23924a4..f46c08a 100644
--- a/cart.ts
+++ b/cart.ts
@@ -1,3 +1,7 @@
export function total(prices: number[]): number {
return prices.reduce((a, b) => a + b, 0);
}
+
+export function tax(amount: number): number {
+ return amount * 0.2;
+}A diff looks strange the first time, so let us read it line by line.
diff --git a/cart.ts b/cart.tssays which file this is about. Thea/andb/are just labels for "the old version" and "the new version".index 23924a4..f46c08ashows the short ids of the old and new content. You can ignore this line for now.--- a/cart.tsand+++ b/cart.tsname the old and new files.@@ -1,3 +1,7 @@is the position marker. It says: "in the old file, this chunk is 3 lines starting at line 1. In the new file, it is 7 lines starting at line 1." Each chunk of change is called a hunk.- Lines that start with a space are unchanged context. Lines that start with
+were added. Lines that start with-were removed. Here, four lines were added and none removed.
Now the important part. There are three different diffs, because there are three areas.
bash
git diff # working directory vs staging area
git diff --staged # staging area vs last commit
git diff HEAD # working directory vs last commitWatch what happens when we stage the file:
text
$ git add cart.ts
$ git diff
$ git diff --staged
diff --git a/cart.ts b/cart.ts
...same diff as before...After git add, plain git diff prints nothing. This confuses almost everyone once. It is not broken. git diff compares the working directory to the staging area, and they are now identical, so there is no difference to show. The change has moved to the next row down: git diff --staged compares the staging area to the last commit, and that is where the difference is now.
Always run git diff --staged just before you commit. It shows exactly what is about to be saved, and it is your last chance to notice a stray debug line.
text
$ git commit -m "Add tax helper"
[main f74fe61] Add tax helper
1 file changed, 4 insertions(+)8. Staging part of a file: git add -p
Earlier we said the waiting room lets you split work into separate commits. So far we staged whole files. What if one file has two unrelated edits?
Say you added a header comment at the top of cart.ts and, further down, a new discount function. Two ideas, one file. Look at the diff:
text
$ git diff
@@ -1,3 +1,4 @@
+// Cart helpers
export function total(prices: number[]): number {
...
@@ -5,3 +6,8 @@ export function total(prices: number[]): number {
export function tax(amount: number): number {
...
+// TODO: discounts
+export function discount(amount: number): number {
+ return amount * 0.9;
+}There are two @@ lines, so there are two hunks. git add -p ("patch") walks through the hunks one at a time and asks about each:
text
$ git add -p
diff --git a/cart.ts b/cart.ts
@@ -1,3 +1,4 @@
+// Cart helpers
export function total(prices: number[]): number {
return prices.reduce((a, b) => a + b, 0);
}
(1/2) Stage this hunk [y,n,q,a,d,j,J,g,/,e,?]? y
@@ -5,3 +6,8 @@ export function total(prices: number[]): number {
...
+export function discount(amount: number): number {
(2/2) Stage this hunk [y,n,q,a,d,K,g,/,e,?]? nWe answered y (yes, stage this) to the first hunk and n (no, not this one) to the second. The other letters: q quits, a stages this and every remaining hunk, d skips this and every remaining hunk, s splits a hunk into smaller ones, e lets you edit the hunk by hand, and ? prints help.
Now the status shows something new:
text
$ git status -s
MM cart.tsMM means: modified and staged (the header comment), and modified again but not staged (the discount function). The same file is in two areas at once, with different parts of its changes in each. Commit what is staged, then stage the rest:
text
$ git commit -m "Add header comment"
[main 634cade] Add header comment
1 file changed, 1 insertion(+)
$ git add cart.ts
$ git commit -m "Add discount helper"
[main 2c7932c] Add discount helper
1 file changed, 5 insertions(+)Two commits, each about one thing. That is what a readable history looks like.
Shortcuts, and why to be careful with them.
| Command | What it stages | The catch |
|---|---|---|
git add file | That one file | None. The safest. |
git add . | Everything new or changed in this folder and below | Also grabs files you forgot about |
git add -A | Everything in the whole repository | Same catch, wider reach |
git commit -a | Every change to tracked files, then commits | Skips new files. And skips your chance to review. |
Check git status before and after git add .. People commit passwords and build folders by accident with it. The next section is the cure.
9. Files Git should never see: .gitignore
Some files do not belong in history: libraries you can re-download (node_modules), build output, log files, and above all secrets such as passwords and API keys in a .env file. You tell Git to ignore them in a file named .gitignore.
text
$ cat .gitignore
node_modules/
*.log
.env
build/Each line is a pattern. Git now pretends matching files do not exist. They will not show up in git status, and git add . will skip them.
text
$ git status -s
?? .gitignoreWe have a .env file, a debug.log file and a node_modules folder in the project, and none of them appear. Only the new .gitignore itself shows up. And you can ask Git why a file is ignored:
text
$ git check-ignore -v .env debug.log node_modules/junk.js
.gitignore:3:.env .env
.gitignore:2:*.log debug.log
.gitignore:1:node_modules/ node_modules/junk.jsEach line reads: file name where the rule is : line number : the rule, then the file it matched. When a file refuses to be ignored, or is ignored and you did not expect it, this is the command that answers why.
The pattern rules you will actually use:
| Pattern | Matches |
|---|---|
*.log | Any file ending in .log, in any folder |
build/ | A folder called build, anywhere |
/todo.txt | Only todo.txt in the top folder, not in subfolders |
docs/*.pdf | PDFs directly inside docs |
**/temp | A temp file or folder at any depth |
!keep.log | An exception: do not ignore this one |
# comment | A comment line |
Commit the .gitignore file itself, so your whole team ignores the same things:
text
$ git add .gitignore
$ git commit -m "Ignore build output, logs and secrets"Three traps.
First: .gitignore only affects files Git is not already tracking. If you committed .env last week and add it to .gitignore today, Git keeps tracking it. Tell Git to stop with git rm --cached .env, which removes it from the repository but leaves the file on your disk.
Second: a secret that was ever committed is still in the history. Removing it later does not remove it from old commits, and anyone who cloned the repository already has it. The only safe response is to treat that password as stolen and change it. Chapter 13.11.4 shows how to remove it from history afterwards. Chapter 8.6.1 covers secrets in general.
Third: some files belong on your computer's ignore list, not the project's. Editor folders (.idea/, .vscode/) and operating system files (.DS_Store) are your business, not the project's. Put those in one personal file and tell Git about it once:
bash
git config --global core.excludesFile ~/.gitignore_globalThat keeps the project's .gitignore short and relevant. Also, you do not have to write .gitignore from nothing. The site gitignore.io and the GitHub gitignore templates give a ready-made list for Node, Python, Java and so on.
10. Renaming and deleting files
You can rename a file in your file explorer, and Git will work out what happened. But Git has its own commands, and they stage the change for you.
text
$ git mv README.md readme.md
$ git status -s
R README.md -> readme.mdgit mv renames the file and stages the rename in one step. The R means renamed.
An interesting detail: Git does not actually record "this file was renamed". It only records the before and after, and then works out the rename by noticing the content is nearly the same. Chapter 13.11.5 explains this.
To delete a file:
bash
git rm old-file.ts # delete the file and stage the deletion
git rm --cached secrets.txt # stop tracking it, but keep the file on diskIf you try git rm on a file with staged changes, Git refuses to protect you from losing work:
text
$ git rm readme.md
error: the following file has changes staged in the index:
readme.md
(use --cached to keep the file, or -f to force removal)That is Git being careful. Read the message, decide what you meant, and use the flag it suggests.
11. Reading history
A history you cannot search is worth nothing. These are the options you will use every week:
bash
git log # full detail, newest first
git log --oneline # one line per commit
git log --oneline --graph # draws the branches (more on the next page)
git log -n 5 # only the last five
git log --stat # which files each commit touched, and how many lines
git log -p # the full diff of every commit
git log --author="Ana" # commits by one person
git log --since="2 weeks ago" # commits after a date
git log -- cart.ts # only commits that touched this file
git log -S"discount" # commits that added or removed this exact text
git show f74fe61 # one commit in full: message and diff
git show HEAD~1 # the commit before the latest (HEAD~2 is two back)The last two deserve a note. git show displays one commit. And HEAD~1 means "one step before HEAD": a way to name a commit relative to where you are, so you do not have to look up ids.
text
$ git log --oneline -S"discount"
2c7932c Add discount helper-S (the "pickaxe") finds the commit where a piece of text first appeared or finally disappeared. When you find a mysterious line in the code and want to know when it was added, this is the fastest answer. Chapter 13.11.7 covers it and its relatives.
12. What a good commit looks like
You now know how to make commits. Here is how to make good ones. The long version is in Chapter 13.11.8; the short version is enough to start with.
One reason per commit. A commit should do one thing that you could describe in a sentence. "Add refund endpoint" is one thing. "Morning's work" is not.
Commit often. A small commit is easy to understand and easy to undo. A commit of three days' work is neither.
Write the message for the person who reads it later. Often that is you, six months from now, trying to remember why a line exists.
text
Reject refunds outside the 30-day window
The endpoint accepted any order id, so support could refund
year-old orders by pasting an old link.A short first line in the imperative ("Add", "Fix", "Reject", not "Added" or "Fixing"), a blank line, and then a few sentences about why. The code already shows what changed. Only the message can say why.
13. The commands from this page
| You want to | Command |
|---|---|
| Start tracking a folder | git init |
| See what is going on | git status (or git status -s) |
| Put a file in the waiting room | git add file |
| Choose pieces of a file | git add -p |
| Save the waiting room as a commit | git commit -m "message" |
| See unstaged changes | git diff |
| See staged changes | git diff --staged |
| See the history | git log --oneline |
| See one commit | git show <id> |
| Rename a tracked file | git mv old new |
| Delete a tracked file | git rm file |
| Keep files out of Git | Write patterns in .gitignore |
What the interviewer will push on
Even simple Git questions are common in interviews, because they quickly show who has used it for real and who has only read about it.
"What is the difference between git add and git commit?" The interviewer is checking whether you know there are three areas. A weak answer: "add saves it, commit saves it permanently". A strong answer names the staging area: add copies the current state of a file into the staging area, commit takes whatever is staged and records it as a permanent snapshot. Then add why the staging area exists: to build clean commits from a messy working day.
"Why does git diff show nothing after I ran git add?" This checks that you understand diff compares two specific areas. Plain git diff compares working directory with staging area, so after staging they match. git diff --staged shows what is queued for the commit.
"How do you undo git add?" The answer is git restore --staged file (older books say git reset file). The common wrong answer is to delete the file, which loses work. Pause and say what it does: it removes the file from the waiting room and leaves your edits in the working directory.
"I added a file to .gitignore but Git still tracks it. Why?" Because ignore rules only apply to untracked files. The fix is git rm --cached file, then commit. A candidate who knows this has fought with it before.
"What is in a commit?" An id (a hash of its contents), the author, the date, the message, a pointer to the previous commit, and a snapshot of every file. Say "snapshot", not "changes". The next chapters show why that matters.
One thing to volunteer: mention that you stage with git add -p and review with git diff --staged before every commit. It signals that you build history on purpose rather than saving whatever happened to change.
Recall
- Git remembers every saved version of a project. A repository is a folder Git watches; its history lives in the hidden
.gitfolder. Delete.gitand the history is gone. - Files live in three areas: the working directory (real files you edit), the staging area (the changes chosen for the next save) and the repository (the saved commits).
git addmoves changes from the first to the second,git commitfrom the second to the third. - The staging area exists so you can build small, clear commits from a messy day.
git add -pstages part of a file, hunk by hunk. - A file is untracked, modified, staged or committed.
git statustells you which;git status -sis the short form (??,M,M,MM). - A commit has an id (a 40-character fingerprint of its contents; the first 7 are enough), an author, a date and a message.
- Three diffs:
git diff(working vs staging),git diff --staged(staging vs last commit) andgit diff HEAD(working vs last commit). Aftergit add, plaingit diffis empty. Run--stagedbefore every commit. .gitignorekeeps files out of Git, but does not affect files already tracked; usegit rm --cached. A committed secret stays in history, so rotate it.- Messages: short imperative first line, a blank line, then why. One reason per commit, and commit often.
Self-test: Name the three areas and the command that moves a change between each. · Why does git diff print nothing right after git add? · What does MM mean in git status -s? · Why can you not fix a leaked password just by deleting the file in a new commit? · What is HEAD~1?
Next: 13.11.2 shows what a branch really is (a sticky note on a commit), how to try an idea without risking main, and what happens when you bring the work back together.