Ignore files in Git

How to Prevent Files and directory from Being Tracked in Git
If we don’t want every file or directory to be tracked in the project by Git. For example, build or output directories, private keys, database passwords, and sensitive information etc. should be kept out of version control. So, how can we make sure Git doesn’t track these types of files?

 

Using the .gitignore File

To prevent certain files or directories from being tracked, we can create a .gitignore file in the root of the project directory. Once we add the ignored file in the .gitignore file, those files will not be tracked by Git and also will not be shown when we run git status. This will help us in keeping the project’s history clean and secure.

 

Ignoring Specific Files and directories

Ignoring files: If we want to ignore any specific files, just add them inside the .gitignore file. For example, if we don’t want to track any log files, we can add *.log to the .gitignore.
Ignoring entire directories: If we want to ignore a whole directory, simply add its name to the .gitignore file. For example, if we don’t want to track any files under the “build” directory, we can add “build/” to the .gitignore.

 

Ignoring specific types of files: We can also ignore entire file types using wildcards. For example, if we want to ignore all .exe files under the build directory, we can add build/*.exe to the .gitignore.

 

Example: Ignoring Specific Files

Let’s say we have five files in the project: myfile1.txt, myfile2.txt, myfile3.txt, myfile4.txt, and myfile5.txt. If we only want to trackmyfile1.txt and myfile3.txt, you can create a .gitignore file and list myfile2.txt, myfile4.txt and myfile5.txt to ignore them.
 
Before adding the files in the .gitignore file
➜ git status
Untracked files:
(use "git add <file>..." to include in what will be committed)
myfile1.txt
myfile2.txt
myfile3.txt
myfile4.txt
myfile5.txt
➜ touch .gitignore
➜ echo "myfile2.txt" >> .gitignore
➜ echo "myfile4.txt" >> .gitignore
➜ echo "myfile5.txt" >> .gitignore
After adding the file in the .gitignore file
➜ git status
Untracked files:
(use "git add <file>..." to include in what will be committed)
myfile1.txt
myfile3.txt
After doing this, if everything works as expected,myfile2.txt and myfile5.txt won’t show up when we check the status with git status. Only myfile4.txt should appear as untracked (since it’s not included in the .gitignore), while myfile2.txt and myfile5.txt are completely ignored.

 

Forcing Git to Track Ignored Files

If we ever need to force Git to track a file that’s in the .gitignore file, we can do so by using the git add -f command. This forces Git to add ignored files, even if they’re listed in .gitignore.