DEV Community

Cover image for How to solve git not ignoring files in .gitignore
Neto Ukpong
Neto Ukpong

Posted on

How to solve git not ignoring files in .gitignore

Git is the number one version control system that has made the software development process faster and collaboration on projects much easier.

When working on a project, there will be some files that don't need to be committed and shared with other developers. Such files include configuration files that are specific to your development environment(.env), IDE config files, log files and node_modules folders.

There are 3 main states of files in a git repository:

  • tracked: These are files/folders that git is aware of and keeps track of any changes made to them.

  • untracked: These are new files/folders in the working directory that are yet to be staged and committed.

  • ignored: These are files/folders that git avoids. No tracking, no staging, no commits on these files/folders.

All ignored files are clearly stated in a .gitignore file.

How to create a .gitignore file

On Windows, run this command in the command line:
cd . > .gitignore

on Mac/Linux
touch .gitignore

Both commands are run from the root directory of the project.

How to correct files/folders not ignored by Git

After creating our .gitignore file and stating the files we want to ignore. Sometimes, they don't get ignored and are committed and pushed to the remote repository. This usually happens when we commit a file/folder either by mistake or otherwise into git before realising the error and then adding the file/folder to .gitignore. In such cases, we run the following commands after committing any changes made:

git rm -r --cached .
git add .
git commit -m "<commit message>"
git push
Enter fullscreen mode Exit fullscreen mode
  • git rm -r --cached . - removes all files from the git index and refreshes the git repository

  • git add . - stages all files/folders not stated in the .gitignore file

  • git commit -m "<commit message>" - commits all files that have been staged

  • git push - push to remote repository

The files stated in .gitignore have been left alone by git and all other files uploaded to the remote repository

Top comments (0)