Git will only ever track files that you explicitly tell it to using git add
. Therefore, there is nothing you need to do: just don't tell Git to track the files you don't want it to track.
This can get annoying if you look at git status
, which will then list all untracked files.
There is an easy solution for that, too: just ignore all files:
echo '*' > .gitignore
This will tell Git to ignore all files. You can still add individual files to the repository using git add -f
(the -f
is necessary to force Git to ignore the fact that the files are ignored).
If you want to use git add .
or git add somedirectory
to add all new files, then you need to individually list all the files to be ignored in .gitignore
. You can use the "annoying" fact I described above, namely that git status
will list all untracked files:
git status --porcelain -uall | grep -E '^\?\? ' | cut -d ' ' -f2- > .gitignore
--porcelain
specifies the output format for git status
to be "Porcelain v1" format. The Porcelain output formats are guaranteed to never change and are designed to be easy to parse by machines, unlike the short or long output formats which are designed to be human-readable and thus may get changed to make them easier to read. -uall
tell git status
to list all untracked files, otherwise it will only list the directory name if all files in a directory are untracked.
The grep
looks for lines beginning with ??
which is how untracked files are listed. The cut
then cuts out everything after the ??
, which is the file name.
Note: this will break with a file named abc\n?? def.txt
, for example. If you have such files, you need to harden the command by e.g. using the -z
flag to git status
which prints the records delimited by ASCII NUL instead of a newline.