(Last Updated On: January 30, 2019)

When you edit the .gitignore file, the rules added only apply to the untracked files. For the files already committed to a remote git repository, you’ll need to unstage them, create a new commit and push to your remote git repository.

I have a directory called backup in my local git repository with two files. Below is the .gitignore file which I have modified to ignore files in this directory.

$ cat .gitignore

Step 1: Unstage the files/directory

Mark the files for unstaging using the git rm -r --cached command.

$ git rm -r --cached backup/
rm 'backup/backup.sh'
rm 'backup/rsync_exclude.lst'

Replace buckup/ with your directory or file.

Step 2: Make new commit

Save your new commit object/changes to local Git repository.

$ git commit -m 'Remove newly ignored directory "./backup"'
master d631061] Remove newly ignored directory "./backup"
2 files changed, 14 deletions(-)
delete mode 100644 backup/backup.sh
delete mode 100644 backup/rsync_exclude.lst

Step 3: Push changes to remote git repository

The previous command saved the changes to the local git repository. Push them to remote repository using the command:

$ git push origin master
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Delta compression using up to 8 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (2/2), 261 bytes | 261.00 KiB/s, done.
Total 2 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To github.com:jmutai/dotfiles.git
7a80a6d..d631061 master -> master

That’s all. You have successfully removed directory/files from remote repository after adding them to the .gitignore file.