Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ignore everything in a git repository subdirectory except a single file?

Tags:

I have a repository with a subdirectory called mod/. I want this subdirectory to be included in the repository along with a README file within it, but I do not want other subdirectories within mod/ to be included. I have tried several fixes proposed here using .gitignore and committing changes, but git status still shows everything in mod/ is being tracked. Currently, my .gitignore contains:

mod/* # Ignore everything in 'mod'...
!mod/README.md # ... except this.

But I have also tried setting the first line to:

/mod
mod/
./mod
./mod/*

and a few other variations...

To 'apply' these settings each time I edit .gitignore, I run:

git rm -r --cached .  
git add .gitignore
git add mod/README.md
git commit -m "banging my head on the wall"
git status

and the status continues to show untracked files in mod/.

like image 312
M. Thompson Avatar asked Jul 18 '18 20:07

M. Thompson


1 Answers

There are three intuitive options I can think of:

  1. Add a separate .gitignore to mod:

    *
    !README.md
    
  2. Use your root level .gitignore, with only either a rule or comment on each line, but not both:

    ./mod/*
    !./mod/README.md
    

    I use ./ prefix here for emphasis, but it is not strictly necessary. Since the paths all contain a non-trailing slash, they will be interpreted relative to the directory of the .gitignore regardless.

  3. Don't use .gitignore for the positive rule: ignore mod, but then do

    git add -f mod/README.md
    

    Git keeps tracking any files that were added using the -f/--force flag.

like image 196
Mad Physicist Avatar answered Sep 28 '22 18:09

Mad Physicist