Tracking changes in Git is essential to manage your files and monitor modifications. This page explains how Git tracks changes and how to use commands to manage your project’s history effectively.
When working with a Git repository:
- Untracked Files: Files that Git does not yet know about.
- Tracked Files: Files that Git is monitoring for changes. Tracked files can be:
- Unmodified: No changes since the last commit.
- Modified: Changes have been made but not yet staged.
- Staged: Changes are prepared for the next commit.
Use git status
to see the current state of your files:
git status
To view changes in files compared to the last commit:
git diff
To view changes that are staged for the next commit:
git diff --cached
To track new files, use the git add
command:
git add filename
To stage all new and modified files:
git add .
You can add specific file types:
git add *.txt
If a tracked file is modified, stage the changes:
git add filename
Use a .gitignore
file to prevent certain files or directories from being tracked:
- Create a
.gitignore
file in your repository:touch .gitignore
- Add patterns for files to ignore. For example:
# Ignore log files *.log # Ignore temporary files *.tmp
- Save the file and commit it:
git add .gitignore git commit -m "Add .gitignore file"
If you no longer want Git to track a file:
- Remove it from tracking without deleting it:
git rm --cached filename
- Commit the change:
git commit -m "Stop tracking filename"
Once files are staged, commit them to save a snapshot of your changes:
git commit -m "Describe your changes"
Scenario | Command |
---|---|
View the current status | git status |
View changes in the working directory | git diff |
Stage a single file | git add filename |
Stage all changes | git add . |
Commit staged changes | git commit -m "message" |
Stop tracking a file | git rm --cached filename |
Ignore files using .gitignore |
Add patterns to .gitignore and commit it |
-
Modify a file:
echo "Hello, Git!" > hello.txt
-
Check the status:
git status
-
Stage the file:
git add hello.txt
-
Commit the changes:
git commit -m "Add hello.txt with a greeting"
Tracking changes is a fundamental part of working with Git. By understanding how Git handles file states and using commands like git status
, git add
, and git commit
, you can efficiently manage your project and maintain a clean version history.
Next Steps: Staging and Committing