Force add despite the .gitignore file

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


See man git-add:

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

So run this

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

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


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


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. Unignore subdirectories of ignored directories in Git
  2. [my eRCaGuy_dotfiles repo with an example .gitignore file containing these notes and demos]: eRCaGuy_dotfiles/.gitignore