GIT Ignore and removing files from GIT

If you want certain files not to be read by git then you can add those files in the .gitignore file.
This is more useful when your application creates log files within the projects itself, or there is a file which when opened with editor it creates temp file(Example Microsoft Word). You don’t those temp files to be visible when you check the status of your repository. Hence you can add the pattern of those temp files in the .gitignore file.

.gitignore for Java

# Ignore Gradle project-specific cache directory

# Ignore Gradle build output directory

So the name of the file is .gitignore and you cannot create this file directly in windows, run the below command in command prompt to create the empty .gitignore file in the root directory of your repository

copy NUL .gitignore

Rules for the patterns you can put in the .gitignore file are below
1. Lines starting with # will be considered as comments and ignored
2. Standard global patterns work and it is applied recursively in the complete files in the project.
3. Patterns starting with / Forward slash are avoided recursively
4. Patterns ending with / Forward slash specified a directory
5. You can negate a pattern by starting it with an exclamation point !

Now you can see some of the sample patterns below

# ignore all .tmp files
# but do track lib.a, even though you're ignoring .a files above
# only ignore the ABC file in the current directory, not subdir/ABC
# ignore all files in any directory named bin
# ignore bin/comments.txt, but not bin/deploy/comments.txt
# ignore all .pdf files in the bin/ directory and any of its subdirectories

Now when we create the file accordingly it will not be shown when we run the GIT status command.

Example : In the below example we have created hello.txt and hello.tmp, but since add .tmp file has to be ignore according to the *.tmp added into the .gitignore file, hence when we run git status -s command after creating hello.txt and hello.tmp only hello.txt is displayed and not hello.tmp. Screenshot of the example below.

Removing files from GIT

Removing files from GIT can be done using git rm command. But just git rm command will not remove the files but only remove the files and put it into staging area, you need to commit the files to actually remove.

git rm <file_name>
git commit -m "Comment"

Removing file from GIT but keeping a copy in local

We can remove the file from GIT but keep the file in local i.e make GIT no longer track the file using the below command

git rm --cached "Removing file from GIT but keeping the file in local"
git commit -m "Comment"

Leave a Comment