← Back to Git Course | Chapter 2: Basic Commands | Lesson 3 of 18

Git Staging Environment

The staging environment is the middle step between editing a file and committing it, letting you choose exactly which changes -- whole files or even individual lines -- go into the next commit.

What is the Staging Environment?

Git tracks a file through three areas: the working directory where you edit files, the staging environment (also called the index) where you mark exactly which changes should go into the next commit, and the repository where committed history is stored permanently.

Example: What is the Staging Environment?

bash
git status

Staging Changes with git add

The staging environment sits between the working directory and the repository, and git add is the command that moves a specific file's current content into it, so only changes that have been explicitly staged are included when you next run git commit.

Example: Staging Changes with git add

bash
git add file.txt

Staging All Changes with git add -A

Rather than staging files one at a time, git add -A scans the entire repository and stages every new file, every modification to a tracked file, and every deletion in a single command, giving a fast way to prepare a commit that includes everything that changed.

Example: Staging All Changes with git add -A

bash
git add -A

Partial Staging with git add -p

git add -p (or --patch) breaks each modified file into individual hunks of changed lines and asks whether to stage each hunk separately, which is useful when a single file contains both changes you want to commit now and changes you'd rather commit separately or not at all.

Example: Partial Staging with git add -p

bash
git add -p

Unstaging Changes

A file that has been staged but not yet committed can be removed from the staging environment with git restore --staged (or the older git reset HEAD), which returns it to the modified state in the working directory without deleting or reverting the actual edits.

Example: Unstaging Changes

bash
git restore --staged file.txt

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.