Files That Do Not Belong in Commits
A project folder often holds files that should never be committed:
- Generated files, such as build output and logs, which any copy of the project can recreate.
- Temporary and personal files, such as scratch notes or editor backups.
- Secrets, such as passwords, API keys and access tokens. Anyone who can read the repository can read a committed secret, and every earlier commit keeps it.
A .gitignore file lists patterns for files Git should leave untracked.
Ignored files disappear from the "Untracked files" list in git status, so
real changes are easier to spot. Commands that add many files at once skip
them. One you will see often is git add ., which stages everything in the
current folder and the folders inside it.
Writing Ignore Rules
Create a file named .gitignore at the top of the repository and write one
pattern per line:
| Pattern | Matches |
|---|---|
notes.tmp | A file or folder with that name, in any folder |
*.tmp | Any name ending in .tmp; * matches anything except / |
build/ | Folders named build, and everything inside them |
/todo.txt | todo.txt at the top of the repository only |
!release.log | Brings back a file that an earlier rule ignored |
# text | A comment; blank lines are skipped too |
When several rules match the same file, the last matching rule wins. That is
why a ! rule must come after the rule it overrides.
Commit .gitignore like any other file, so everyone who works on the project
gets the same rules. Rules apply only to untracked files; the next section
shows what that means for files you have already committed.
To find out which rule ignores a file, ask Git:
git check-ignore -v build/app.log
.gitignore:2:build/ build/app.log
The output names the rules file, the line number and the pattern, then the path. If no rule ignores the path, the command prints nothing.
Ignored Versus Already Tracked
Adding a rule does not affect a file Git already tracks. If a file was
committed before the rule existed, Git keeps recording its changes, and git check-ignore does not report it at all.
To stop tracking a committed file but keep it on your disk, remove it from the staging area only:
git rm --cached .env
The next commit records the file as deleted from the project, while your copy stays in the folder. From then on, the ignore rule applies to it. Two warnings:
- Without
--cached,git rmalso deletes the file from your folder. It refuses only when the file has edits you have not committed. - When other people later receive that commit, Git deletes the file from their folders, as it does for any file a commit removes. Tell them to keep a copy first if they need one.
Untracking changes only the commits you make from now on. Earlier commits still
contain the file exactly as it was, and git log -p -- <file> shows it.
If a Secret Was Committed
Treat any real secret that reached a commit as exposed, and respond in this order:
- Revoke or rotate the secret first, at the service that issued it: create a new key and delete or disable the old one. This is the only step that makes the leaked value useless, so do it even if you also clean up the repository.
- Stop tracking the file and ignore it, as in this lesson's exercise, so the secret is not committed again.
- Removing it from earlier commits is a separate job. It means rewriting history, which is outside this course, and it cannot reach copies other people already have, such as their clones. That is why revoking comes first.
Hosting services can catch some mistakes before they spread. On GitHub.com, push protection for users is on by default and blocks pushes to public repositories when it detects a secret in them. Treat that as a safety net, not as a replacement for keeping secrets out of commits.
The habits that prevent leaks are simple: add ignore rules for secret files
before creating them, keep real values out of example files, and check
git status and git diff --staged before every commit.
Exercise: Ignore Generated Files and Untrack a Committed One
The practice repository has a build folder, a scratch file and a settings
file, .env, that was committed by mistake. You will ignore all three and stop
tracking .env without deleting it.
Starting state: Git configured as in the configuration lesson. The key in
.env is fake; never put a real secret in a practice repository.
-
Run the setup:
mkdir -p ~/git-practice/ignore-rules cd ~/git-practice/ignore-rules git init -b main cat > app.py <<'EOF' print("Weather app") EOF cat > .env <<'EOF' WEATHER_API_KEY=not-a-real-key EOF git add app.py .env git commit -m "Add weather app" mkdir build cat > build/app.log <<'EOF' Build finished. EOF cat > notes.tmp <<'EOF' Scratch notes EOF -
Look at the starting state:
git statusbuild/andnotes.tmpare listed under "Untracked files"..envis not listed: it is tracked and unchanged. -
Write the rules, then check the status again:
cat > .gitignore <<'EOF' # Build output build/ # Temporary files *.tmp # Local settings and secrets .env EOF git statusOnly
.gitignoreremains under "Untracked files". The build folder and the scratch file are now ignored. -
Confirm which rule ignores each file:
git check-ignore -v build/app.log notes.tmp.gitignore:2:build/ build/app.log .gitignore:4:*.tmp notes.tmp -
Change
.envand see whether its rule hides the change:cat > .env <<'EOF' WEATHER_API_KEY=another-fake-key EOF git status git check-ignore -v .envgit statuslistsmodified: .env, andgit check-ignoreprints nothing. The rule has no effect, because.envis tracked. -
Stop tracking
.envand check that the file is still there:git rm --cached .env git status ls -aGit prints
rm '.env'.git statusshowsdeleted: .envunder "Changes to be committed", and.envis not listed as untracked, because the rule now applies to it.ls -ashows that.envis still in the folder. -
Commit the rules and the removal together, then check:
git add .gitignore git commit -m "Stop tracking .env and ignore generated files" git status git check-ignore -v .envThe commit summary includes
delete mode 100644 .envandcreate mode 100644 .gitignore.git statusreportsnothing to commit, working tree clean, andgit check-ignorenow finds the rule:.gitignore:6:.env .env -
Look for the old key in history:
git log -p -- .envTwo commits appear. "Add weather app" shows
+WEATHER_API_KEY=not-a-real-keyand the newest commit shows the same line removed. The value is still in history, which is why a real key would need revoking.
Success: git status is clean; git check-ignore -v names a rule for
build/app.log, notes.tmp and .env; .env is still on your disk; and you
found the old key in history.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
A file still shows as modified after you add its rule | It was committed before the rule existed | git rm --cached <file>, then commit |
git check-ignore -v prints nothing | The file is tracked, or no rule matches its path | Check git status; compare the path with your patterns |
.gitignore is listed as untracked | Expected: it is an ordinary file | Add and commit it so everyone shares the rules |
A ! rule does not bring back a file inside an ignored folder | Git does not look inside a folder that is ignored as a whole | Ignore the contents with build/* instead of build/, then add the ! rule after it |
The following paths are ignored by one of your .gitignore files | You named an ignored file in git add | Leave it ignored; Git's hint shows how to force it if you really mean to |
error: the following file has local modifications | You left out --cached, and Git refused to delete a file with uncommitted edits | Run git rm --cached .env |
| A committed file is missing from the folder | git rm ran without --cached on a file with no uncommitted edits | git restore --staged <file>, then git restore <file>, brings back the committed version; the next lesson explains both |
-
Clean up:
cd ~/git-practice ls rm -rf ignore-rules ls
Independent task: before cleaning up, create two log files and add rules so
that every .log file is ignored except release.log:
cat > debug.log <<'EOF'
Debug output
EOF
cat > release.log <<'EOF'
Release notes
EOF
Write the rules yourself, then confirm with
git check-ignore -v debug.log release.log and git status.
Check Your Understanding
- A teammate adds
config.localto.gitignore, but every edit still showsmodified: config.local. Why, and how can they stop tracking it without losing their copy? - You pushed a commit containing a real API key an hour ago. What do you do first, and why is deleting the file not enough?
Answer and Reasoning
Independent task
Add these lines to the end of .gitignore:
cat >> .gitignore <<'EOF'
# Logs, except the release log
*.log
!release.log
EOF
git check-ignore -v debug.log release.log then prints:
.gitignore:8:*.log debug.log
.gitignore:9:!release.log release.log
Your line numbers may differ if you wrote the rules differently. The second
line starts with !: the last rule matching release.log brings it back, so
it is not ignored. git status lists release.log as untracked and
.gitignore as modified, and does not mention debug.log. The order matters:
with !release.log above *.log, the later *.log rule would win and ignore
both files.
Understanding check
config.localwas committed before the rule existed, and ignore rules apply only to untracked files, so Git keeps tracking it. They should rungit rm --cached config.localand commit with the rule in place. Git then stops tracking the file and their copy stays on disk.- Revoke or rotate the key first, at the service that issued it. Deleting or untracking the file only affects new commits: the pushed commit still contains the key, and anyone who copied the repository has it. Revoking makes the leaked value useless. Removing it from history is a separate job that cannot reach existing copies.