This guide teaches you to record your changes in Git, step by step. You
will follow the daily working cycle: check the state of your files
(status), choose what goes into the next commit (add), review the
differences (diff), then create the commit. You will also learn to
exclude unwanted files with .gitignore.
Prerequisites: an initialized Git repository. Understanding the 3 states of Git (Working Directory, Staging Area, Repository).
What you will learn
- The life cycle of files: untracked → unmodified → modified → staged
git status: see the state of each filegit add: place changes in the Staging Areagit diff: inspect what has changedgit commit: record a snapshot in the history.gitignore: exclude files that must not be versioned
The life cycle of files
Git puts each file of your project in one of four states: untracked, unmodified, modified or staged. The diagram shows the three places where your work lives: the working directory (your files), the Staging Area (also called the index, what will leave with the next commit) and the repository (the history). The arrows show the commands that move a file from one to another.
An untracked file is a file that Git does not know yet. As soon as you add
it with git add, Git starts tracking it and it becomes staged.
After a commit, the file is unmodified until your next change, which makes
it modified: it then waits for a new git add.
Check the state with git status
You will run git status very often: it shows the state of each file.
git statusExpected output (a repository with files in different states):
On branch mainChanges to be committed: (use "git restore --staged <file>..." to unstage) new file: index.html
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: style.css
Untracked files: (use "git add <file>..." to include in what will be committed) script.jsThis output tells you three things:
index.htmlis in the Staging Area, ready to be committedstyle.cssis modified but not staged yetscript.jsis untracked, Git does not know it yet
Stage files with git add
The git add command moves files from the Working Directory to the
Staging Area. This is the selection step: you choose exactly which
changes to include in your next commit.
Add a specific file
Naming the file is the safe reflex: you stage exactly what you want, and nothing else. It is especially useful when your directory contains work in progress that you are not ready to commit.
git add index.htmlAdd several files
You can write several names on the same line: Git stages them all in one go.
This form gives you control over what goes into the commit, which
git add . does not.
git add index.html style.css script.jsAdd all modified and untracked files
git add .This command adds everything in the current directory and its subdirectories.
It is convenient, but first check with git status that you are not about to
stage unwanted files.
What happens if you modify a file after git add?
The commit records what is in the Staging Area, not what is on your disk. If
you modify style.css after staging it, the new change stays out of the index
until a new git add. git status then shows the file in both lists:
Changes to be committed: (use "git restore --staged <file>..." to unstage) modified: style.css
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: style.cssThe first list describes the staged version, the one that will leave with the
next commit. The second describes the more recent changes, which will not.
Run git add style.css again so that the final version is recorded.
Add parts of a file (interactive staging)
To stage only some of the changes in a file, use patch mode:
git add -p style.cssGit shows you each block of changes (called a hunk, see the Git vocabulary (in French)) and asks what to do with it:
diff --git a/style.css b/style.cssindex 5324dac..f540e30 100644--- a/style.css+++ b/style.css@@ -1,5 +1,6 @@ body { font-family: sans-serif;+ color: #333; margin: 0; padding: 0; }(1/1) Stage this hunk [y,n,q,a,d,e,p,?]?The main options:
| Key | Action |
|---|---|
y | Stage this hunk |
n | Do not stage this hunk |
q | Quit (stop offering hunks) |
s | Split the hunk into smaller pieces, when possible |
Interactive staging lets you create clean, focused commits, even when you made several changes in the same file.
Inspect differences with git diff
Before committing, inspect what has changed to check that your changes are correct.
See unstaged changes
git diffThis command compares the Working Directory with the Staging Area. It shows
what you have modified but not yet added with git add.
Expected output:
diff --git a/style.css b/style.cssindex 5324dac..f540e30 100644--- a/style.css+++ b/style.css@@ -1,5 +1,6 @@ body { font-family: sans-serif;+ color: #333; margin: 0; padding: 0; }Lines prefixed with + are additions, those prefixed with - are
deletions. The context (lines without a prefix) helps you locate the
changes.
See staged changes (ready to commit)
git diff --stagedThis command compares the Staging Area with the last commit. It shows exactly
what will be recorded by the next git commit.
Summary of the diff commands
The distinction to remember is about the two points of comparison. A plain
git diff looks at what is not staged yet, git diff --staged looks at what
already is. This difference often puzzles beginners: a git diff that shows
nothing does not mean the work is empty, but often that everything is already
in the Staging Area. The third line, git diff HEAD, combines both and shows
the total gap with the last commit.
| Command | Compares | Shows |
|---|---|---|
git diff | Working Dir ↔ Staging | Unstaged changes |
git diff --staged | Staging ↔ Last commit | What will be committed |
git diff HEAD | Working Dir ↔ Last commit | All changes to tracked files |
Here is git diff HEAD in the repository of the git status example above:
index.html is staged, style.css is modified, and script.js is not
tracked.
git diff HEADdiff --git a/index.html b/index.htmlnew file mode 100644index 0000000..bd54434--- /dev/null+++ b/index.html@@ -0,0 +1,3 @@+<!DOCTYPE html>+<html>+</html>diff --git a/style.css b/style.cssindex 5324dac..f540e30 100644--- a/style.css+++ b/style.css@@ -1,5 +1,6 @@ body { font-family: sans-serif;+ color: #333; margin: 0; padding: 0; }The diff combines the staged file and the modified file, but script.js does
not appear in it: as long as a file is untracked, git diff HEAD does not see
it. Stage it with git add script.js to make it appear.
Create a commit
A commit records the content of the Staging Area as a new snapshot in the history. Each commit is identified by a unique SHA and carries a descriptive message.
Commit with an inline message
With the -m option, the message fits on one line and Git does not open an
editor. It suits changes that one sentence describes entirely. As soon as the
change deserves an explanation of the why, prefer the form without -m,
detailed just below.
git commit -m "Add the home page and base styles"Output obtained with Git 2.47.3, for the very first commit of a repository:
[main (root-commit) 4335e40] Add the home page and base styles 2 files changed, 45 insertions(+) create mode 100644 index.html create mode 100644 style.cssThe (root-commit) mention appears only for the first commit, the one that has
no parent. The following commits show only [main 3f7a2b1], with their own
abbreviated SHA.
Commit with a detailed message
For more complex changes, open your editor to write a message on several lines:
git commitGit opens the configured editor. Write a short title (50 characters max), an empty line, then a detailed description:
Add user authentication
- Create the login form (login.html)- Validate input on the client side (auth.js)- Style the form (auth.css)Shortcut: add and commit in one command
For files already tracked by Git (not new files):
git commit -am "Fix the text color"The -a option automatically adds the already tracked files that were modified
to the Staging Area, then commits. Untracked files are not included.
Amend the last commit
Did you forget a file or make a typo in the message?
git add forgotten-file.cssgit commit --amendGit opens the editor to change the message, and the forgotten file is included in the commit. The commit SHA changes, because its content is different.
Write good commit messages
A good commit message helps to understand the history of the project. Here are common conventions. This course writes titles in the imperative ("Add", "Fix"). The past tense ("Added") or a noun form ("Addition of the contact page", used in the history examples of browse the history) are also common: what matters is that a repository keeps a single register.
| Rule | Example |
|---|---|
| Short title (50 chars max) | Add the contact page |
| Verb in the imperative | Add rather than Added |
| Empty line after the title | Separates the title from the body |
| Optional body (72 chars/line) | Explains the why, not the what |
Remove files from the index
Unstage a file (without losing the changes)
If you added a file to the Staging Area by mistake:
git restore --staged style.cssThe file goes back to the "modified" state in the Working Directory. Your changes are not lost.
Stop tracking a file in Git
To delete a file and remove it from Git tracking:
git rm old-file.txtTo stop tracking a file without deleting it from the disk (useful if you committed it by mistake):
git rm --cached secret-file.envThe file stays on your disk but Git no longer tracks it. Remember to add it
to .gitignore to avoid staging it again. Be careful: this command removes
nothing from the commits already made. A secret committed by mistake stays
readable in the history and must first be revoked, as the lesson
Why version your work (in French)
explains.
Configure the .gitignore
The .gitignore file tells Git which files and folders to ignore. These
files will no longer appear in git status and will never be staged by
git add ., unless they are already tracked.
This section covers what you need to know to get started. For the three
sources of rules, checking what Git actually takes into account with
git check-ignore, and the case of the already tracked file that no rule
filters any more, see the dedicated guide
ignore files with .gitignore (in French).
Basic syntax
Each line of the .gitignore is a pattern. Two characters do all the work:
* stands for any sequence of characters, and / at the end of a line
designates a whole folder. The most counter-intuitive point is !, which
brings back a file that a previous pattern excluded; the order of the lines
therefore matters, an exception must come after the rule it contradicts.
# Comment*.log # All .log filesnode_modules/ # The whole node_modules folder!important.log # Exception: track this file despite *.logbuild/ # Build folder.env # Environment file (secrets)The most common patterns
These patterns cover the usual needs. Look mostly at the last two, which are
subtler: doc/**/*.pdf uses the double asterisk to go through all
subfolders, whereas a leading /, as in /TODO, anchors the pattern to the
root of the repository and does not affect TODO files located deeper.
Confusing these two behaviors often explains a file you thought was ignored
that still shows up in git status.
| Pattern | Matches |
|---|---|
*.log | All files ending in .log |
build/ | The build folder and all its content |
doc/**/*.pdf | All .pdf files in doc/ and its subfolders |
!README.md | Exception: do not ignore this file |
/TODO | Only the TODO file at the root |
.gitignore templates by language
GitHub maintains a collection of .gitignore templates for each language and
framework:
github.com/github/gitignore.
A few common examples:
__pycache__/*.py[cod].venv/*.egg-info/dist/.envnode_modules/dist/.env*.logcoverage//bin/*.exe*.testgo.workTroubleshooting: common problems
Most blockages in the add then commit cycle come down to a few recurring
symptoms. Read this table from left to right: start from the message or the
behavior you observe, then apply the solution. One puzzling case is the
git diff that shows nothing, explained above: it almost always comes from
changes that are already staged.
| Symptom | Likely cause | Solution |
|---|---|---|
git add does not add a file | The file is in .gitignore | Check .gitignore or use git add -f file |
| File committed by mistake | Already in the history | git rm --cached file + add it to .gitignore |
git diff shows nothing | Changes already staged | Use git diff --staged |
nothing to commit, working tree clean | All files are committed | Normal: make a change and start again |
| Wrong commit message | Typo | git commit --amend (if not pushed yet) |
Key takeaways
git statusruns before everyaddand everycommitgit addplaces changes in the Staging Area;-ppicks the hunks one by one, and a change made after staging needs a newgit addgit diff(unstaged) andgit diff --staged(staged) show what is going to be recordedgit commit -m "message"records the snapshot in the history.gitignoreprotects your repository from unwanted files, create it before the first commit- Never commit secrets:
.env, keys, tokens → in the.gitignore
Knowledge check
Check that you have grasped the essentials of this guide. The questions cover only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Browse Git history with git log
A new full quiz with random questions
Work again only on the questions you missed