2

When you inherit a code base where gitignore has not been used then the first thing you want to do is add a standard gitignore file like this one Standard Visual Studio gitignore file for example. But the problem is that a bunch of files that match the patterns in that gitignore file have already been added. It is tedious to go through the project and stop tracking the specific files in the various folders like the .vs and debug folders. Is there a git command or a series of git commands that can automate this for us by looking at the gitignore file and stop tracking the files that match the patterns in that gitignore file?

I have searched on Stack Overflow for this and there are some answers but they seem to not rely on the gitignore file to find the files needed to stop tracking.

1 Answer 1

6

If it is a single branch thing, you could do:

git rm -r --cached . # delete everything from index but do not delete it on the FS
git add . # now add everything back into index. Ignored stuff should be ignored... make sure to add the hidden files... _specially_ .gitignore
git commit -m "Removing ignored files"

Or something like that.

That should be enough to get rid of all the stuff that you want to ignore. If it's a multiple-branch thing, consider using that as a script and run it for every branch.

And if what you mean is that you would like for all of that stuff to go away from branch history, consider using git filter-repo

Sign up to request clarification or add additional context in comments.

5 Comments

I just tried this out on a dummy project and it seems to work well. Is there no side effect by using this method?
What kind of thing are you thinking about? E.g. If anything matches an ignore rule that you actually want/need - it’ll get deleted, but there’s no mystery or magic with these commands. One can always recover the deleted files from a previous commit if necessary.
Nothing should get deleted on the FS "for real". That's why I used --cached
Indeed - apologies, poor wording on my part.
I am not sure. I am just scared running these delete commands and I am trying to figure out if it will have any side effects that I do not want. But reading about the commands used and trying it on a simple dummy project seems to confirm that this is actually doing what I wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.