Ignore Files With .gitignore

Learn to exclude files that we don’t want to track.

How can we prevent files/folders from being tracked?

Mostly, we don’t want to add everything into version control. Some files are never tracked. Generally, we would like to ignore the build and output folders. We also want to ignore the private key, passwords for databases, and secret hashes for applications.

  • Ignore files: We can create a .gitignore file at the base of the project folder. The .gitignore file allows us to list files that we don’t want to track at all. These files won’t appear as Untracked files when viewing the git status result.

  • Ignore folders: We can ignore an entire folder by specifying the folder name.

  • Ignore certain types of files: We can ignore certain types of files with the wildcard character—for example, build/*.exe. Suppose we have five files, but we don’t want to track file2.txt and file5.txt. We make a .gitignore file at the root of our project folder and add the file names we want to ignore. We add and commit only file1.txt and file3.txt. So, if .gitignore works, only file4.txt should appear as an untracked file in the git status result and not file2.txt and file5.txt.

Note: We can still force add files that are ignored using the git add -f option.

Commands to be executed

Try out these commands in the terminal given below. The .gitignore file already contains file2.txt and file5.txt:

$ git add file1.txt file3.txt
$ git commit -m "Initial commit with File 1 and 3"
$ git status

Get hands-on with 1200+ tech skills courses.