How to override and include files ignored by gitignore

2022-10-12 Wed 00:00

I needed to include a jar file in my Git, but all of the jar files were ignored with the *.jar notation in the gitignore file. I didn't know how to do this so I looked it up, and also decided to write about it.

How to override gitignore

This StackOverflow post pretty much describes how to do this, but I'm going to reiterate what he described just in case the post disappears. All credit goes to Suragch (the person who posted the answer).

You can override to include a file with the ! syntax. You can control which files are included with the usual syntax like * and **. You can check the details about the gitignore syntax in the docs.

Example

As an example, lets say that there is a line *.txt in the .gitignore file.

When you want to include a single file:

!myfile.txt

When you want to include a directory:

!mydir/*

When you want to include a directory and its subdirectories:

!mydir/**

Sample .gitignore

*.txt

!myfile.txt

!mydir/**

# afile.txt: ignored
# adir/afile.txt: ignored

# bdir/myfile.txt: included
# mydir/subdir/afile.txt: included

That's it!