273

How can I add an exception to .gitignore, like "ignore all the .dll files BUT myfile.dll"?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pistacchio
  • 56,889
  • 107
  • 278
  • 420

5 Answers5

357

Use ! to negate the pattern:

*.dll
!myfile.dll
Ben James
  • 121,135
  • 26
  • 193
  • 155
235

If you want to ignore whole folder, except some specific files, then write:

MyFolder/*
!MyFolder/CoolFile.txt

This won't work:

MyFolder/
!MyFolder/CoolFile.txt
cubuspl42
  • 7,833
  • 4
  • 41
  • 65
  • 34
    Note that this extends to subdirectories as well. For example, this will work: `MyFolder/sub/* !MyFolder/sub/file.txt` But this won't: `MyFolder/* !MyFolder/sub/file.txt` – ben Jan 14 '15 at 15:39
  • 13
    The reason - " It is not possible to re-include a file if a parent directory of that file is excluded. Git doesn’t list excluded directories for performance reasons, so any patterns on contained files have no effect, no matter where they are defined. " [https://git-scm.com/docs/gitignore] – Craig Hicks Jun 21 '17 at 03:51
  • 5
    So "for performance reasons" I have to manually enter 21 different subfolders that have the same name and were previously ignored by a single line, just so I can exclude one file. – endolith Jul 21 '20 at 03:23
  • 1
    @endolith, have you found a better way to do it? – Angelin Calu Oct 18 '22 at 10:39
48

You can also ignore folders like

!src/main/resources/archetype-resources/**/*

you can also ignore nested folder with patterns like

!**/src/test/resources/**/*

For quick creation of .gitignore file try gitignore.io

Anver Sadhat
  • 3,074
  • 1
  • 25
  • 26
14

I did this because I have a folder called /modules that I want to ignore, except everything in the /modules/custom folder. This worked for me. Now my custom modules will get synced to GitHub.

/modules/*
!/modules/custom/
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Robbiegod
  • 954
  • 4
  • 14
  • 44
13

You can have several .gitignore files working together in a hierarchical manner to achieve your goal. At the root level you may have:

root

*.dll

inside the folder having the myfile.dll you can add another .gitignore file like so:

root/lib/folderwithMyFiledll

!myfile.dll

more info here

An optional prefix "!" which negates the pattern; any matching file excluded by a previous pattern will become included again. Put a backslash ("\") in front of the first "!" for patterns that begin with a literal "!", for example, "!important!.txt". It is possible to re-include a file if a parent directory of that file is excluded if certain conditions are met. See section NOTES for detail.

kamayd
  • 420
  • 6
  • 10
  • 2
    The doc snippet you pasted seems out of date. The site currently states that you can't re-include files under parent directories. – vivainio Jan 04 '19 at 14:57