Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "!" do in gitignore files?

I don't quite understand this

I've read the official documentation on it from https://git-scm.com/docs/gitignore

An optional prefix "!" which negates the pattern; any matching file excluded by a previous pattern will become included again. 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. Put a backslash ("\") in front of the first "!" for patterns that begin with a literal "!", for example, "!important!.txt".

I have this gitignore file

/media/*
!/media/xmlconnect

What does this do exactly? I'm ignoring all subdirectories inside /media/, but am I making an exception to /media/xmlconnect (e.g. I'm NOT gitignoring it?)

so basically I'm gitignoring everything but media/xmlconnect?

like image 805
Vincent Tang Avatar asked Jun 01 '17 16:06

Vincent Tang


People also ask

What goes in a Gitignore file?

A gitignore file specifies intentionally untracked files that Git should ignore. Files already tracked by Git are not affected; see the NOTES below for details. Each line in a gitignore file specifies a pattern.

What is exclamation mark in Gitignore?

An exclamation mark can be used to match any character except one from the specified set. debug[a-z].

What is the purpose of a .gitignore file?

gitignore files. This file lists files that are intentionally untracked and should be ignored by Git. It is important to note that changes to files that were staged before being added to the . gitignore file will continue to be tracked by Git.

What should I ignore in Gitignore?

gitignore only works for ignoring files that are not being tracked by Git yet. Adding an already tracked file to . gitignore will not prevent you from commiting changes to that file.


2 Answers

/media/*

The above ignores all the files inside media

However, if you want to make an exception and do not want to ignore media/xmlconnect then you use !.

!/media/xmlconnect

When you do a git add . , only media/xmlconnect will be added to git, rest all other files inside media will not be added.

edited: reversing the order in .gitignore:

Git applies patterns in .gitignore in order of appearance, so if we reverse the order and !/media/xmlconnect comes before /media/*, it will ignore all the files in media directory.

You can check out this issue to learn about the fix proposed.

like image 176
slal Avatar answered Sep 29 '22 21:09

slal


Exactly, this is used to un-ignore a path that is ignored before that line. Your example illustrates the use case pretty good.

You are ignoring everything inside media except xmlconnect.

like image 22
Juan José Bueno Montoya Avatar answered Sep 29 '22 20:09

Juan José Bueno Montoya