Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the working directory and the git Index?

The git book defines the git index:

The Git index is used as a staging area between your working directory and your repository. You can use the index to build up a set of changes that you want to commit together. When you create a commit, what is committed is what is currently in the index, not what is in your working directory.

But I am still having a difficult time understanding it, especially the highlighted statement that "what's committed is not what's in my working directory".

So far, in my limited working with git, everything in the working directory is always committed, if I do:

git add <all new files in the working directory>
git commit -a -m "git will refuse to commit without this comment" 

git then commits all modified files as well as all new files.

So, in effect, my working directory is the staging area?

I am not sure then what the git index is and how it is interpreted as the staging area.

Could you please explain?

like image 686
WinWin Avatar asked Jul 09 '11 14:07

WinWin


3 Answers

The answer in your particular case is that you are understanding the documentation correctly, but using the "shortcut" command to commit your entire working directory.

If you run git commit -a -m "Message" then your working directory is treated like it is the staging area. This is convenient sometimes, but you lose the ability to use the index as designed. Try the following command:

git commit -m "Message"

If you do this instead, you can use the staging area to commit only part of the changes you have made to your working directory.

like image 106
Clueless Avatar answered Oct 14 '22 15:10

Clueless


The index is a copy of the directory tree managed by git. Initially, it is a copy of what is in the HEAD commit. git add copies files from the working directory to the index. git commit creates a new commit from what is in the index.

The index is like a buffer-- it is not stored in the git history but access to it is controlled by git (unlike your working directory, which can be accessed in any number of ways). git commits from the index so what is committed is something that git controls.

like image 29
antlersoft Avatar answered Oct 14 '22 14:10

antlersoft


The index/staging area is NOT your working directory. You can do a simple test to see this. Create a file in your working directory called, say, foo. Add some text to the file. Then do git add foo. Now edit foo again and add (or remove) some more text.

If you run git diff --cached (which shows what's in the index), you'll only see foo as it was after the first round of edits and subsequent git add. If you do git diff (which shows what's changed in your working directory), you will see all of the additional modifications you have made since the git add.

like image 34
siride Avatar answered Oct 14 '22 13:10

siride