The Git Add Command
By using the Git add command, you are adding file contents to the index. Files in the index can be part of a commit. You can specify this when doing the actual commit.
It is important to know that "The index holds a snapshot of the content of the woking tree". Pay attention to the word "snapshot". It means that the index holds the content of the file(s) at the time they have been added to it.
As a result, when you added a file by using the add command, changed it afterwards and want to perform a commit, the file will be committed with its contents when added, not the current contents. This leads to the conclusion that,
- "after making any changes to the working tree, and before running the commit command, you must use the add command to add any new or modified files to the index"
- the add command can be performed multiple times before doing a commit
How to use the add command
You can specify what to add in several ways. Firstly, you can specify a single file:
git add file1.txt
It is also possible to specify multiple files at once:
git add file1.txt file2.txt
When specifying a folder to add, you will add all files and subfolders with their files:
git add folderName
The add command makes it also possible to add all files and folders contained in your current working directory:
git add .
You can use the Git status command to "obtain a summary of which files have changes that are staged for the next commit".
Because files are added with their contents when the add command was performed, you can get an output like the following when using the Git status command:
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: file1.txt
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
This output indicates that file1.txt was added at some point. Which is why it is listed below “changes to be committed”. Later on, changes have been applied to file1.txt which have not been added yet. Therefore, it is listed below “Changes not staged for commit”, too.
For full reference see Git add documentation.
Watch it on YouTube
You can watch me explaining the
git add command in this video: