Tracking Files
We learned about the different file states in the beginning of this module. In this lesson, we'll learn how to move files between states.
Tracked vs Untracked Files
Before a file can be version-controlled, we have to tell Git to start tracking it. In essence, a file that you want to have controlled by Git is tracked, while files you want Git to ignore are untracked. Once a file is tracked, it will receive the benefits of version control.
When you first create a new Git repository, all existing files are untracked.
Check File Status
To check the state of files within your Git repository, run:
git statusThis message means that there are no untracked files in your repository, and none of your previously tracked files have been modified:
On branch mainnothing to commit, working tree cleanOn the other hand, if there were untracked files in your repository, the status message would look like something like this:
On branch main
Untracked files: file_a.txtThis message tells us we have an untracked file in our repository: file_a.txt.
Track a File
To tell Git to start tracking your file(s), use the add command, which takes a list of files to be tracked. If we continue with our example from the previous section, use the following command to tell Git to start tracking file_a.txt:
git add file_a.txtThis command moves the untracked file (in this case, file_a.txt) to the staging area. Adding a file to the staging area is the first step to tracking it. Now that we've staged the file, we need to add it to our Git repository to start tracking using the git commit command.
git commit -m 'Adding file_a to the repository'The above command takes all the files in your staging area, bundles them into a commit and saves them to your Git repository. Any untracked files in your staging area will be converted to tracked files by this operation. The -m flag specifies a commit message that describes what the commit contains.
Track Multiple Files
You may have a lot of files that you'd like Git to start tracking. This is a common scenario after initializing a Git repository in an existing project directory. To add all untracked files to the staging area, use . instead of a filename in the git add command:
git add .After staging all your untracked files, simply commit them to your Git repository to start tracking (remember to add a descriptive message using -m):
git commit -m 'Initial commit of untracked files'In addition to untracked files, git add . also stages modified files as well. For now, consider using git add . only right after initializing a repository using git init. We'll dissect this behavior in the next lesson and learn how to safely use git add . in other scenarios.