Use .gitignore File After the Fact

Normally, the .gitignore file will not ignore a file or directory once that file or directory has been committed to the repo. So if you create your .gitignore file after the fact for some reason, what do you do?

To use the .gitignore file after commits have been made to the file or directory you wish to ignore, do the following.

You may wish to remove the files from both your local and the git repository. Or, you might wish to keep your local working copy and remove the file(s) from the git repository with an after the fact .gitignore file. Read on to review how to do this.

remove the local working copy

If you wish to remove the local working copy of  the file or directory, use git rm to remove the file or directory from git.

git rm -r some_directory

The effect of git rm instead of simply rm, is the same as if you were to use rm to remove a file or directory and then follow it up with git add <file>. The next commit will then inform git that the file(s) are to be deleted in the repository.

Eg.

git rm -rf some_directory

git add <some_directory>

After the fact ignore file: Remove files from git index while keeping your local working copy

git rm --cached  will remove the file(s) or directories from the git index  while keeping your local working copy in tact.

eg.

If I wanted to remove a directory, say, the node_modules directory and all its children and then be able to add node_modules to a new .gitignore file, I could do this:

git rm -r node_modules –cached

Then create the new .gitignore file with node_modules in it.

echo “node_modules” | cat >> .gitignore

Now, after committing the changes, the repo will ignore the local working node_modules directory.

 

 

Posted in

Leave a Reply

Your email address will not be published.