Managing Tracked and Untracked Files
Now that you understand the difference between tracked and untracked files, let's explore how to manage them in your Git repository.
Adding Untracked Files
To add an untracked file to the Git repository, you can use the git add
command. This will stage the file for the next commit.
$ git add example_untracked.txt
After running this command, the file example_untracked.txt
will be considered a tracked file.
Removing Tracked Files
If you want to remove a tracked file from the Git repository, you can use the git rm
command. This will remove the file from the repository and your working directory.
$ git rm example_tracked.txt
Ignoring Untracked Files
As mentioned earlier, you can create a .gitignore
file to specify patterns for files that should be ignored by Git. This is useful for excluding files that are not relevant to your project, such as compiled binaries, log files, or temporary files.
Here's an example .gitignore
file:
## Compiled source files
*.com
*.class
*.dll
*.exe
*.o
*.so
## Log files
*.log
## Temporary files
*.swp
*.tmp
With this .gitignore
file, any files matching the specified patterns will be considered untracked by Git, and you won't have to worry about them being added to the repository accidentally.
Restoring Untracked Files
If you accidentally delete an untracked file, you can restore it using the git clean
command. This command will remove any untracked files from your working directory.
$ git clean -f
The -f
option tells Git to force the removal of the untracked files.
By understanding how to manage tracked and untracked files, you can keep your Git repository organized and ensure that only the necessary files are being tracked and committed.