Git Foundations / Record Your Work

Ignore files and keep secrets out

Lesson 9 of 33. Open to read. No account needed.

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:

PatternMatches
notes.tmpA file or folder with that name, in any folder
*.tmpAny name ending in .tmp; * matches anything except /
build/Folders named build, and everything inside them
/todo.txttodo.txt at the top of the repository only
!release.logBrings back a file that an earlier rule ignored
# textA 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 rm also 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:

  1. 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.
  2. Stop tracking the file and ignore it, as in this lesson's exercise, so the secret is not committed again.
  3. 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.

  1. 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
    
  2. Look at the starting state:

    git status
    

    build/ and notes.tmp are listed under "Untracked files". .env is not listed: it is tracked and unchanged.

  3. Write the rules, then check the status again:

    cat > .gitignore <<'EOF'
    # Build output
    build/
    # Temporary files
    *.tmp
    # Local settings and secrets
    .env
    EOF
    git status
    

    Only .gitignore remains under "Untracked files". The build folder and the scratch file are now ignored.

  4. 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
    
  5. Change .env and see whether its rule hides the change:

    cat > .env <<'EOF'
    WEATHER_API_KEY=another-fake-key
    EOF
    git status
    git check-ignore -v .env
    

    git status lists modified: .env, and git check-ignore prints nothing. The rule has no effect, because .env is tracked.

  6. Stop tracking .env and check that the file is still there:

    git rm --cached .env
    git status
    ls -a
    

    Git prints rm '.env'. git status shows deleted: .env under "Changes to be committed", and .env is not listed as untracked, because the rule now applies to it. ls -a shows that .env is still in the folder.

  7. 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 .env
    

    The commit summary includes delete mode 100644 .env and create mode 100644 .gitignore. git status reports nothing to commit, working tree clean, and git check-ignore now finds the rule:

    .gitignore:6:.env	.env
    
  8. Look for the old key in history:

    git log -p -- .env
    

    Two commits appear. "Add weather app" shows +WEATHER_API_KEY=not-a-real-key and 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 seeLikely causeNext step
A file still shows as modified after you add its ruleIt was committed before the rule existedgit rm --cached <file>, then commit
git check-ignore -v prints nothingThe file is tracked, or no rule matches its pathCheck git status; compare the path with your patterns
.gitignore is listed as untrackedExpected: it is an ordinary fileAdd and commit it so everyone shares the rules
A ! rule does not bring back a file inside an ignored folderGit does not look inside a folder that is ignored as a wholeIgnore the contents with build/* instead of build/, then add the ! rule after it
The following paths are ignored by one of your .gitignore filesYou named an ignored file in git addLeave it ignored; Git's hint shows how to force it if you really mean to
error: the following file has local modificationsYou left out --cached, and Git refused to delete a file with uncommitted editsRun git rm --cached .env
A committed file is missing from the foldergit rm ran without --cached on a file with no uncommitted editsgit restore --staged <file>, then git restore <file>, brings back the committed version; the next lesson explains both
  1. 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

  1. A teammate adds config.local to .gitignore, but every edit still shows modified: config.local. Why, and how can they stop tracking it without losing their copy?
  2. 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

  1. config.local was committed before the rule existed, and ignore rules apply only to untracked files, so Git keeps tracking it. They should run git rm --cached config.local and commit with the rule in place. Git then stops tracking the file and their copy stays on disk.
  2. 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.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 99 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy