Let’s say you have a bunch of files you don't want in your repo (like .class or .ctxt files?) but you've already pushed them! (doh!)
And you'd like add them to your .gitignore so that git will ignore them moving forward; these files will still be present in your repository unless you delete them. This article we will see how to get rid of them.
Step 1: Commit all your changes
Before proceeding, make sure all your changes are committed to your local repo, including your .gitignore file. MAKE SURE, you've added to the .gitignore file all the patterns you'd like to ignore going forward (like those pesky .class files).
git commit -m "before git ignore purge"
Step 2: Remove everything from the repository
To clear your repo, use:
git rm -r --cached .
rm is the remove command
-r will allow recursive removal
–cached will only remove files from the index. Your files will still be there.
The . indicates that all files will be untracked. You can untrack a specific file with git rm --cached foo.txt (thanks @amadeann).
The rm command can be unforgiving. If you wish to try what it does beforehand, add the -n or --dry-run flag to test things out.
This removes all your project files from your local repo copy, but NOT from your local working directory.
Step 3: Add everything back
git add .
This adds back all your working directory files (making sure to git-ignore any files from the .gitignore file) to your local staging area.
Step 4: Commit (enforcing the new .gitignore)
git commit -m ".gitignore fix and cleanup"
This commits all your staging area files to your local repository. Your repository is now clean of all the files you wanted to get rid of.
Now Push the changes from your local repository to your remote repository to see the changes effective there as well. (and double check it by looking at Github!)