3

I recently initiated a git repo and forgot to add a .gitignore file. After my initial commit, my repo has many subdirectories and many files that should have been ignored. Is there an efficient way to add a .gitignore and then push the repo without the files meant to be ignored to a tool like GitLab or GitHub?

Brian Fitzpatrick
  • 2,755
  • 3
  • 23
  • 43
  • Have the files that should be ignored been committed? – Stephen Kitt Oct 29 '18 at 18:57
  • Yes. I realized that I was missing my gitignore file after I committed. – Brian Fitzpatrick Oct 29 '18 at 18:59
  • It sounds like you want to edit the previous commits & remove the mistakenly committed files as well? If so, you'd have to rewrite history — which means any clones of the repository will need a force push/pull. There are tools for doing this; but if you've just created the repository and have no history in it, probably easier to just start over with a new git repository & do a correct initial commit there. Also, have you looked for answers on [so]? There are a lot of git experts there, and I suspect you'll find answers explaining how to do this over there... – derobert Oct 29 '18 at 19:52
  • (of course, you're welcome to ask it here, just pointing to [so] as a resource where you might find a quick answer) — for example, https://stackoverflow.com/questions/7927230/remove-directory-from-remote-repository-after-adding-them-to-gitignore and https://stackoverflow.com/questions/13541615/how-to-remove-files-that-are-listed-in-the-gitignore-but-still-on-the-repositor and https://stackoverflow.com/questions/43463687/how-to-filter-history-based-on-gitignore – derobert Oct 29 '18 at 19:53
  • I'd be happy to simply remove what should be ignored and recommit. I guess I was hoping for a quick scripting solution. Maybe something that loops through each line of `.gitignore` and uses `find` to remove all of the undesired files. – Brian Fitzpatrick Oct 29 '18 at 20:09

1 Answers1

1

If you don’t mind deleting all the ignored files in the working directory, the following will stage all committed-but-ignored files for deletion:

find . -print0 | git check-ignore -z --stdin --no-index | xargs -0 git rm -f -r --cached --ignore-unmatch --

(assuming GNU find and a recent enough git for git check-ignore). It will also delete any other ignored file or directory.

This lists all files and directories starting from the current directory, checks whether they’re ignored (even if they’re committed), and delete them, regardless of whether they’re committed, untracked etc.

This works with any .gitignore files in the tree (or even elsewhere in your git configuration).

Follow up by committing the changes and pushing them; since the changes are a new commit, you won’t need to force-push anything. Rewriting history to remove all references to supposedly ignored files is a slightly more involved task.

Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164