Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying .gitignore to committed files

Tags:

git

I have committed loads of files that I now want to ignore. How can I tell git to now ignore these files from future commits?

EDIT: I do want to remove them from the repository too. They are files created after ever build or for user-specific tooling support.

like image 881
user880954 Avatar asked Sep 23 '11 11:09

user880954


People also ask

How do you Gitignore a file that is already committed?

If you want to ignore a file that you've committed in the past, you'll need to delete the file from your repository and then add a . gitignore rule for it. Using the --cached option with git rm means that the file will be deleted from your repository, but will remain in your working directory as an ignored file.

Should I include .gitignore In commit?

Normally yes, . gitignore is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG or something. In those cases you probably don't want to force that on anyone else.

Can I add Gitignore after?

No. Even with an existing . gitignore you are able to stage "ignored" files with the -f (force) flag. If they files are already commited, they don't get removed automatically.


1 Answers

After editing .gitignore to match the ignored files, you can do git ls-files -ci --exclude-standard to see the files that are included in the exclude lists; you can then do

  • Linux/MacOS: git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
  • Windows (PowerShell): git ls-files -ci --exclude-standard | % { git rm --cached "$_" }
  • Windows (cmd.exe): for /F "tokens=*" %a in ('git ls-files -ci --exclude-standard') do @git rm --cached "%a"

to remove them from the repository (without deleting them from disk).

Edit: You can also add this as an alias in your .gitconfig file so you can run it anytime you like. Just add the following line under the [alias] section (modify as needed for Windows or Mac):

apply-gitignore = !git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached 

(The -r flag in xargs prevents git rm from running on an empty result and printing out its usage message, but may only be supported by GNU findutils. Other versions of xargs may or may not have a similar option.)

Now you can just type git apply-gitignore in your repo, and it'll do the work for you!

like image 177
Jonathan Callen Avatar answered Sep 28 '22 02:09

Jonathan Callen