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 Git staging area lets you:
-
Select 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.
-
Review changes in the staging area before committing them permanently to ensure they are correct and complete. This helps catch any unintended modifications or additions before they become part of the repository's history.
-
Work incrementally: finish one bit, add the changes to the staging area; continue working on other parts, and then add more changes later. This flexibility allows you to build up a self-contained stable set of changes gradually over time.
-
Separate work-in-progress from the completed stuff. If you messed up something, you can always discard and revert the unstaged changes without touching the staged ones.
Examples
View the status of the staging area and your workspace:
git statusAdd a single file to the staging area:
git add myfile.txtAdd 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 appears 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