Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between .gitignore rules with and without trailing slash like /dir and /dir/

Tags:

git

gitignore

Is there a difference between /dir and /dir/ in the .gitignore file within a Git repository?

How are the following different?

/dir /dir/ /dir/* 
like image 512
Srikanth AD Avatar asked Jul 26 '13 18:07

Srikanth AD


People also ask

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.

What does double asterisk mean in Gitignore?

A trailing " /** " matches everything inside. For example, " abc/** " matches all files inside directory " abc ", relative to the location of the . gitignore file, with infinite depth. A slash followed by two consecutive asterisks then a slash matches zero or more directories.

What should Gitignore include?

gitignore should list the names or name-patterns of files that will be found in work-trees when working with your project, but that should not be committed to the project. In other words, it's not OS-specific, it's project-specific.


1 Answers

This is a old question, but high ranked on Google and the top voted answer is wrong. Here goes the correct answer.

Yes, these rules are different.

  • /dir will match a file, directory, link, anything named dir
  • /dir/ will match only a directory named dir
  • /dir/* will match all files, directories and anything else inside a directory named dir (but not the dir directory itself).

/dir, /dir/ and /dir/* are NOT equivalent. The difference is very clear when using overriding rules, like the famous !.gitkeep to get around the limitation of tracking empty directories. Suppose the existence of the file dir/.gitkeep

  • With /dir and /dir/, Git won't even look inside the directory so the .gitkeep won't be seen.
  • With /dir/*, the file will be detected by Git and the directory will be kept if this .gitkeep is committed, because the rule doesn't apply to the directory itself, only to its contents.

OBSERVATION: All the rules mentioned above are anchored at the current directory (the place where the .gitignore is), because of the / prefix. Without the prefix, the rules would apply not only for that specific directory, but also for the sub-directories or everywhere in the repository, if the .gitignore is located at the root level.

like image 170
Victor Schröder Avatar answered Sep 18 '22 16:09

Victor Schröder