'how to add all currently untracked files/folders to git ignore?

I initialized the git repository and made a first commit. Now, in this directory I run ./configure and ./make all so that it populates a lot of extra files/folders don't want to track.

What I would like to do, is to add all those untracked files once and for all to my gitignore. Is there any simple way to do it?

I can get rid of some unnecessary files like *.o or *.mod by specifying appropriate lines in .gitignore, but this does not solve the problem.



Solution 1:[1]

Try this:

git status -s | grep -e "^\?\?" | cut -c 4- >> .gitignore

Explanation: git status -s gives you a short version of the status, without headers. The grep takes only lines that start with ??, i.e. untracked files, the cut removes the ??, and the rest adds it to the .gitignore file.

Solution 2:[2]

A simpler command to do this is

git ls-files --others --exclude-standard >> .gitignore

You might want to edit the result to replace repeated patterns with wildcards.

Solution 3:[3]

If your working tree is clean except for the untracked files/folders, a shorter solution is possible using awk:

git status -s | awk '{print $2}' >> .gitignore

Solution 4:[4]

in the accepted answer, the grep part was causing me problem (i.e. was not filtering, instead all lines including those starting with M (modified) were shown as well), and replacing "^\?\?" with "^??" solved it for me. I am on win 10 and using it in msys2's bash.

Solution 5:[5]

This works too when there are spaces in the untracked stuff and is shorter:

git status -s | grep -oP '^\?\? "?\K[^"]+' >>.gitignore 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mrks
Solution 2 poolie
Solution 3
Solution 4 user8395964
Solution 5 Karioki