One of the most essential concepts to Git is that of the staging area. Its use can fundamentally change how you work, for the better! Let’s go over how exactly it works and what you’ll need to know to use it.
With most other version control systems, there’s 2 places to store data: your working copy (the folders/files that you’re currently using) and the datastore (where the version control decides how to pack and store your changes). In Git there’s a third option: the staging area (or index). It’s basically a loading dock where you get to determine what changes get shipped away.
Since the working directory and what gets saved by Git are essentially decoupled, this allows the developer to build up their commits however they want, and not in a fashion where the VCS tells you. Since there’s a layer between when Git actually saves the data, you gain a lot more flexibility and control.
Using the index is quite simple with the git add
and git commit
commands. Basically, you add
files onto the index, and once you’re satisfied with the changes commit
them:
Once they’re in the repository you can push
them to remote locations, merge
them into other branches, and much more. There’s also actions that can be performed on the staging area itself, such as temporarily stashing your changes.
Let’s go through just a basic example of using the staging area. I just made some changes:
$ git status On branch master Changed but not updated: (use "git add <file>..." to update what will be committed) modified: README.md modified: about.html Untracked files: (use "git add <file>..." to include in what will be committed) help.txt no changes added to commit (use "git add" and/or "git commit -a")
So in this example we have 2 files that Git knows about, and one it does not: help.txt. If we do git add .
, that will add everything that has been changed or any new files that have not been tracked yet. The add command doesn’t store the data yet, it simply places it on the loading dock, ready for the next git commit
truck to ship it away.
$ git add . $ git status On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: README.md modified: about.html new file: help.txt
Just like the prompt says, you can use git reset HEAD <file>
to restore files back to their modified state. This way, you can commit exactly what you wanted. You can also commit specific lines of files if you really wanted. If you’re wondering about how to revert files, there’s a whole tip dedicated to that as well. From here, doing a git commit
will move all of the files into Git’s data storage, and you’re set!
$ git commit -m "Adding stuff" Created commit e793200: Adding stuff 2 files changed, 3 insertions(+), 0 deletions(-) create mode 100644 help.txt
If you’re looking for more information on the index, check out these fantastic posts:
If you know of other resources that explain the index, let us know in the comments!