Key concepts

Staging area

The staging area (also known as the index) is one of Git's internal mechanisms that lets you pick particular changes in project files to store permanently as part of the next commit (think of a snapshot/checkpoint) in your Git repository.

Q: Why do you need to pick particular changes? Why not just save everything?

A: You can absolutely do that too. However, in real work it's common to end up making changes that are unrelated to each other even if you plan otherwise.

For example, while working on a new feature, you might randomly stumble upon a typo in a variable name in the existing code or update some lacking documentation. These changes are unrelated to the feature, and it's often better to commit them separately. This way, if you need to revert the feature later, you won't accidentally revert the typo fix or documentation update.

The staging area serves several purposes:

  1. Selective commits: You can choose which changes to include in the next commit by adding only the desired files or portions of files to the staging area. This allows you to create focused and meaningful commits that address specific tasks or features.

  2. Review changes: Before committing, you can review the changes in the staging area to ensure they are correct and complete. This helps catch any unintended modifications or additions before they become part of the repository's history.

  3. Incremental updates: The staging area enables you to stage changes incrementally. You can add changes to the staging area, continue working on other modifications, and then add more changes later. This flexibility allows you to build up a commit gradually over time.

  4. Separation of concerns: By using the staging area, you can separate the process of making changes in your working directory from the act of committing those changes to the repository. This separation provides a clear distinction between work in progress and completed work ready to be recorded in the repository's history.

Examples

View the status of the staging area and your workspace:

git status

Add a single file to the staging area:

git add myfile.txt

Add all changes in a directory to the staging area:

git add src/

The . character below points to the current directory, meaning "all changes in the current directory." When run from the root of your repository, this stages all changes in the entire repository:

git add .

Commit the staged changes to your repository's history with a given message:

git commit -m "Add feature XYZ or fix bug ABC"

Remove all changes from the staging area (but don't undo the actual changes):

git restore --staged .

The . character again. Here, it means "remove all changes in the current directory from the staging area."

You can also specify a particular file or directory:

git restore --staged path/to/file.txt
© 2024-2025 GitByBit.All rights reserved.