Force add despite the .gitignore file

GitGitignore

Git Problem Overview


Is there a way to force git to add a file despite the .gitignore file?

Git Solutions


Solution 1 - Git

See man git-add:

   -f, --force
       Allow adding otherwise ignored files.

So run this

git add --force my/ignore/file.foo

Solution 2 - Git

Despite Daniel Böhmer's working solution, Ohad Schneider offered a better solution in a comment:

If the file is usually ignored, and you force adding it - it can be accidentally ignored again in the future (like when the file is deleted, then a commit is made and the file is re-created.

You should just un-ignore it in the .gitignore file like this: Unignore subdirectories of ignored directories in Git

Solution 3 - Git

How to UNignore some select contents (files or folders) within an ignored folder

If you have ignored the contents of a directory like this:

/ignored_dir/*    # ignore the **contents of** this dir!

then you can UNignore a file or directory inside there like this:

!/ignored_dir/special_file_to_include   # Do NOT ignore this file--DO include it!
!/ignored_dir/special_dir_to_include/   # And do NOT ignore this dir--DO include it!

BUT, if you have ignored the "ignored_dir" directly like this instead:

/ignored_dir/     # ignore this directory **directly**

then the above ! rules which attempt to UNignore some files or folders will NOT work! So, in that case, switch from using this style: /ignored_dir/ to this style: /ignored_dir/*, and then add your ! rules as shown above to UNignore something within that dir!

References:

  1. https://stackoverflow.com/questions/5261959/unignore-subdirectories-of-ignored-directories-in-git/5285539#5285539
  2. [my eRCaGuy_dotfiles repo with an example .gitignore file containing these notes and demos]: eRCaGuy_dotfiles/.gitignore

Solution 4 - Git

Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarkView Question on Stackoverflow
Solution 1 - GitDaniel BöhmerView Answer on Stackoverflow
Solution 2 - GitA-SView Answer on Stackoverflow
Solution 3 - GitGabriel StaplesView Answer on Stackoverflow
Solution 4 - GitshardyView Answer on Stackoverflow