Skip to content

How to ignore files that have already been pushed to remote

Problem

Sometimes we want to ignore some files from the remote repository, but simply adding them to the .gitignore file won't ignore them because they are already present on the remote repository.

Solution

Let's say we want to remove a folder named target which is usually used for builds that we don't want on the remote repository.

The first step is to create a .gitignore file in the root directory

Let's create it by using touch command.

sh
touch .gitignore

Then, add target in the .gitignore file. The file contents will look like this:

.gitignore

target

Now, ignore and remove the target folder from the remote repository

sh
git rm -r --cached target

This will remove all files in the target folder.

Now, you can add .gitignore file and commit it.

If you only want to remove a single file, then remove the -r flag from the command

For example, to remove a temp.txt file you would use a command like this:

sh
git rm --cached temp.txt

That's all. Problem solved!