Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

By updated

Improve this page

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 file
  • git add: place changes in the Staging Area
  • git diff: inspect what has changed
  • git 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.

The three states of Git: git add moves modified files from the working directory to the staging area, git commit records them in the .git repository; git restore --staged and git restore go the other way.git addgit commitgit restore --stagedgit restore fileWorking directorymodified filesStaging areanext snapshotRepository .gitfull history
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

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.

Terminal window
git status

Expected output (a repository with files in different states):

On branch main
Changes 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.js

This output tells you three things:

  • index.html is in the Staging Area, ready to be committed
  • style.css is modified but not staged yet
  • script.js is 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.

Terminal window
git add index.html

Add 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.

Terminal window
git add index.html style.css script.js

Add all modified and untracked files

Terminal window
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.css

The 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:

Terminal window
git add -p style.css

Git 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.css
index 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:

KeyAction
yStage this hunk
nDo not stage this hunk
qQuit (stop offering hunks)
sSplit 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

Terminal window
git diff

This 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.css
index 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)

Terminal window
git diff --staged

This 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.

CommandComparesShows
git diffWorking Dir ↔ StagingUnstaged changes
git diff --stagedStaging ↔ Last commitWhat will be committed
git diff HEADWorking Dir ↔ Last commitAll 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.

Terminal window
git diff HEAD
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..bd54434
--- /dev/null
+++ b/index.html
@@ -0,0 +1,3 @@
+<!DOCTYPE html>
+<html>
+</html>
diff --git a/style.css b/style.css
index 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.

Terminal window
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.css

The (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:

Terminal window
git commit

Git 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):

Terminal window
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?

Terminal window
git add forgotten-file.css
git commit --amend

Git 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.

RuleExample
Short title (50 chars max)Add the contact page
Verb in the imperativeAdd rather than Added
Empty line after the titleSeparates 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:

Terminal window
git restore --staged style.css

The 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:

Terminal window
git rm old-file.txt

To stop tracking a file without deleting it from the disk (useful if you committed it by mistake):

Terminal window
git rm --cached secret-file.env

The 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 files
node_modules/ # The whole node_modules folder
!important.log # Exception: track this file despite *.log
build/ # 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.

PatternMatches
*.logAll files ending in .log
build/The build folder and all its content
doc/**/*.pdfAll .pdf files in doc/ and its subfolders
!README.mdException: do not ignore this file
/TODOOnly 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/
.env

Troubleshooting: 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.

SymptomLikely causeSolution
git add does not add a fileThe file is in .gitignoreCheck .gitignore or use git add -f file
File committed by mistakeAlready in the historygit rm --cached file + add it to .gitignore
git diff shows nothingChanges already stagedUse git diff --staged
nothing to commit, working tree cleanAll files are committedNormal: make a change and start again
Wrong commit messageTypogit commit --amend (if not pushed yet)

Key takeaways

  • git status runs before every add and every commit
  • git add places changes in the Staging Area; -p picks the hunks one by one, and a change made after staging needs a new git add
  • git diff (unstaged) and git diff --staged (staged) show what is going to be recorded
  • git commit -m "message" records the snapshot in the history
  • .gitignore protects 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

10 questions
6 min
70% to pass

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