Ignore Files With .gitignore
Learn to exclude files that we don’t want to track.
We'll cover the following
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 asUntracked files
when viewing thegit 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 trackfile2.txt
andfile5.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 onlyfile1.txt
andfile3.txt
. So, if.gitignore
works, onlyfile4.txt
should appear as an untracked file in thegit status
result and notfile2.txt
andfile5.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 1400+ tech skills courses.