Coda Chang Coda Chang - 2 months ago 37
Git Question

.gitignore work wrongly, file disappear when checkout branch

I felt a little bit confused about

. Here's the thing, I developed in
, and I don't want the
to be uploaded into

I thought that I only need to edit these two file on the
, so I add them into

Then I run

git rm --cached secrets.yml database.yml

to clean my
track file status.

Therefore, these two file are still in the folder, but they can't be added into
track list.

However, I found out when I
and then come back. These two files will disappeared, what happened?


Git stores these files for each branch individually. So you could have the same files with different contents on many branches. You can also have the files on one branch and have them removed from another branch (which is probably what you currently have).

In case you already pushed your files to Github, the secrets are already public and should be changed ASAP. Do not just remove the files, you can never be sure nobody copied them!

As mentioned in the comments, you can filter-branch the files out and force-push the repository, but this would break some things if there are other people who have checked out the repository. I'd rather remove the file from all branches using git rm --chached and push the branches to keep a stable history and change the secrets.

You can remove the files automatically from all branches:

for branch in $(git for-each-ref --format='%(refname)' refs/heads/); do
    git checkout "$branch"
    git rm --cached config/secrets.yml config/database.yml
    git commit -m 'Remove secrets.yml'
echo "Remember to git push"

If you haven't pushed the branches yet, you can filter the files out (taken from this answer):

git filter-branch --index-filter 'git rm --cached --ignore-unmatch config/secrets.yml config/database.yml' --all