Ignore files that have already been committed to a Git repository [duplicate]
Asked Answered
P

21

2832

I have an already initialized Git repository that I added a .gitignore file to. How can I refresh the file index so the files I want ignored get ignored?

Performing answered 16/7, 2009 at 19:26 Comment(0)
S
4708

To untrack a single file that has already been added/initialized to your repository, i.e., stop tracking the file but not delete it from your system use: git rm --cached filename

To untrack every file that is now in your .gitignore:

First commit any outstanding code changes, and then, run this command:

git rm -r --cached .

This removes any changed files from the index(staging area), then just run:

git add .

Commit it:

git commit -m ".gitignore is now working"

To undo git rm --cached filename, use git add filename.

Make sure to commit all your important changes before running git add . Otherwise, you will lose any changes to other files.

Please be careful, when you push this to a repository and pull from somewhere else into a state where those files are still tracked, the files will be DELETED

Sostenuto answered 16/7, 2009 at 19:26 Comment(41)
be aware to commit all your changes before, otherwise you will loose control on all the changed filesBreast
This doesn't seem to stay on a push or a clean clone. any ideas?Spend
@TravisWebb You would have to make sure you set up .gitignore first. Also I tend not to remove all files from the index, only the ones I need to by using Fileglobs such as *.oAlphosis
Does this break any continuity for the files I do want to keep tracked?Psychoanalysis
@boomhauer It doesn't, just checked.Blepharitis
i did this and it said i had 100s of files changed afterwards. i did a revert and now, finally, my .gitignore is working properly and ignoring my *.user file. thanks!Unrefined
git rm -r --cached . removed way more files than was in the git ignore for me :( :(. It removed files in directories that I don't even have listedFaught
Does git rm -r --cached actually remove everything from the index? By definition, the index is just the staging area, the place where files are before you commit. Or are there 2 definitions of "index"? (btw, it was successful for me)Antistrophe
OMG I was so afraid that this deleted all of my previous commits bc for some reason it took some time for my previous commits to appear in Xcode x_x Thank goodness they are still there!Anglonorman
this doesn't work for me. xcode 4.5 still tracks the user interface state file. grrr. what to do?Fantastic
This is the go to solution for properly .gitignoring files that you were previously tracking. Like... if you start a project by tracking everything (git add .) and then later figure out that you want to .gitignore application/config/database.php (without doing what @Performing says to do in his answer above, git will just continue to track the contents of the application/config/database.php file).Carr
it didn't work for me either. Mine has subfolders.Misguided
For future readers you may need these references about the command used on the answer. kernel.org/pub/software/scm/git/docs/git-rm.html kernel.org/pub/software/scm/git/docs/git-add.htmlRobbierobbin
I needed to do a push after the three commands to get this to work. I am using git on http://tfs.visualstudio.com/. I also did a sync, but the push should be sufficient.Danidania
Great answer but git rm --cached filename seems a little less drastic imho..Evocative
@JimMorrison you miss the point. if you have a large project with a complicated .gitignore (such as a C# project in Visual Studio) figuring out each individual file to remove is tedious. these three simple commands fixes everything painlessly.Syncretism
This is an old question now and some people are saying it didn't/doesn't work for them. I have just tried it out and can confirm it works for me on git version 1.8.2.1.Tractate
I get this error fatal: pathspec '' did not match any filesMisnomer
If you are unsure about running git rm --cached filename, you can do git rm --cached --dry-run filename to see what it is going to do. Also remember -r for directories.Strudel
For a not so brute forced method I use: git rm -r --cached some-directory This removes all files that are gitignored. After this call something like this: git commit -m 'Remove the now ignored directory "some-directory"' git push origin masterStandice
Hi @takeshin, where does git push fit into this flow?Ligule
Not a very helpful answer. I did remove all, un-tracked a file but it committed the deletion of file to live repository once it was set as ignored. Misguiding answer I would say. It SHOULD NOT HAVE git rm -r --cached . at the first place. It removes them all while one wouldn't want to.Diffraction
@ArvindK. Did you do a git add . after remove? this answer removes all files, then re-adds non-ignored ones perfectly for me (with a slightly complex .gitignore), there shouldn't be any auto-commit to a live repos...Milagrosmilam
be aware, when using this with "git ftp" it happily removes your file from the ftp server!!!Trinl
Worked as advertised :) however, there's no update to the git repo? All those "old" files are still checked in there.... is there way to update it?Illstarred
@Sostenuto This worked form me on my local repo, however when I pushed to remote (my staging environment) it removed files completely from staging. Is there a way to just have it just ignore files on remote as well.Assyriology
Got scared at first seeing all of the 'rm' files! :) Then 'kept calm' and read on. It seems to have worked.Leonidaleonidas
Worked perfectly for me to remove a set of directories with multiple subfolders containing images that I did not wanted to be stored on GitHub.Avarice
Make sure you use git push afterwards or else this won't workWailful
What will happen to other project members that already had the new gitignore, when they pull this new commit? Will the files be removed from their computers, or are they preserved "as is" because gitignore is making sure a git pull does not affect these files?Grille
Don't miss the small dot at the end of the 2 first commands! (woops)Escallop
In case you forgot to commit your changes before executing above command and lost all the changed file, use git reset HEAD~1 to undo your last commit(recover your lost files). and use git reset HEAD . if you only run git rm -r --cached .Elwoodelwyn
I lost track of all my submodules. Hadn't seen that mentioned here.Buskined
I tried this process and it only ever works if i commit directly after step 1. Otherwise if I delete files from ignored directory, the changes still appear in git.... Is that what the edit at the end of the answer is saying?Levi
If this branch is pulled into master does it still work?Meteoric
I had to add "f" to force removal: git rm -rf --cached .Truditrudie
Best way I've found was add the ".idea" directory and after remove it with --cached . In the process, the "./idea/workspace.xml" appeared aparently from nothing! I've repeated the process with the file, and again with the ".idea" directory. Pretty annoying procedure! But works!Auto
I cannot count the amount of times I come back to this solution.Bar
Please be careful, when you commit and push this to a repository and pull from somewhere else into a state where those files are still tracked it wil REMOVE themCaducity
this works excellently to remove the cached files from versions subsequent to this commit, but what if I'm trying to ignore a file because it unneeded and takes up a lot of space? I presume an object for the first version of this file is still referenced by the first commit involving it, right? If I rebase and commit my changes to a commit at or before the problematic files were added, will the underlying objects be garbage collected?Nevus
git rm -r --cached . for me also remove all the project filesSchoolmaster
E
733

If you are trying to ignore changes to a file that's already tracked in the repository (e.g., a dev.properties file that you would need to change for your local environment but you would never want to check in these changes), then what you want to do is:

git update-index --assume-unchanged <file>

If you want to start tracking changes again:

git update-index --no-assume-unchanged <file>

See git-update-index(1) Manual Page.

Also have a look at the skip-worktree and no-skip-worktree options for update-index if you need this to persist past a git-reset (via)


Update: Here's a convenient alias for seeing which files are currently "ignored" (--assume-unchanged) in your local workspace

git config --global alias.ignored = !git ls-files -v | grep "^[[:lower:]]"
Epiblast answered 6/7, 2012 at 17:9 Comment(19)
This is genius! Brilliantly useful. Do you know if there's a way to get a list of all the 'on hold' files?Legitimize
This'll work for you: git ls-files -v If the character printed is lower-case, the file is marked assume-unchanged. see: https://mcmap.net/q/12434/-can-i-get-a-list-of-files-marked-assume-unchanged and: git-scm.com/docs/git-ls-filesEpiblast
This only works as long as one of your remotes doesn't have a change to that file that conflicts with what you have.Maxilliped
If you need to integrate a change, from outside your local, to files to which you've assume-unchanged you can always assume-changed, stash, pull/merge, stash pop and assume-unchanged again.... it's not uncommon to add a property, for example, that each local would want to retrieve this way.... but this is really for files where changes most likely WILL conflict... e.g. usernames or local paths... that's the point really.Epiblast
@Epiblast Does this only affect myself? Or all users?Karie
@Karie This only affects the locally checked out file(s) and does not affect origin or any other checked out copies of the repo.Epiblast
Here's my slightly more verbose version of the ignored alias, as it appears in my ~/.gitconfig file: ignored = !git ls-files -v $(git rev-parse --show-toplevel) | (grep '^[[:lower:]]' || echo 'None ignored.') && echo '\nIgnore changes with: git update-index --assume-unchanged <file> \nor track again with: git update-index --no-assume-unchanged <file>' The toplevel part of it makes sure it searches the entire repository.Coquille
This works well for modified files, but I cannot get it to work for files I have deleted on local machine but do not wish to delete from repo. Any idea how to get locally deleted files to stop showing up in commit window ?Sabellian
Unfortunately --assume-unchanged doesn't work with git stash: the changes are reverted during git stash and not reapplied during git stash pop. See this question.Forgive
This is a great way to see files that you've hidden with assume-unchanged, and thus I think you should call the alias 'hidden' not ignored. To me ignored files are ones that git doesn't look at because they match a pattern in .gitignore. You can find these files via git status -s --ignored | grep '^!!'Pulvinate
I'll just add to this that this command won't work on a file if it's staged. Make sure you unstage it if somehow it got in the staged state first. I mean this command will still work on it but it will remain in your list and won't drop off. So just make sure you unstage.Foreworn
@ScottWeldon maybe skip-worktree would be a good alternative.Furcula
Not sure if the syntax is different on mac but I had to modify the alias slightly git config --global alias.hidden '!git ls-files -v | grep "^[[:lower:]]"'Mayfield
The exclamation mark in your alias messes up with most shells. Maybe should you quote it, or add the simple command without any alias: git ls-files -v | grep '^[[:lower:]]'Horoscopy
@CrhistianRamirez Thanks for your syntax, its worked great for the alias !Hildebrandt
Apparently, Git does NOT approve this approach. Here in this FAQ, it says git does NOT provide a way to ignore changes to a tracked file, and git update-index should NOT be used this way.Chole
@Chole That's a great point. Best practice for a config file would be to check in one with an import statement to a local.config which would NOT be checked in and safely ignored. That said, not every developer (especially in large organizations) has control over how files are tracked in a repo, this gives you a reasonable workaround, one which hasn't failed me personally in over 10 years.Epiblast
@Epiblast Good workaround indeed! I didn't think of that use case. But I personally ran into this problem when I used this approach. But I guess you never had this kind of problem? #69187786Chole
@leonard oh yeah... I get that on occasion, but the workaround is right there in the error text, simply stash your changes, switch branches (or pull or whatever) and then un-stash your changes. I've used aliases that stash/pull/stash-pop over the years as well.Epiblast
I
384

To untrack a file that has already been added/initialized to your repository, ie stop tracking the file but not delete it from your system use: git rm --cached filename

Ideography answered 14/9, 2010 at 23:55 Comment(5)
This was the perfect way to remove the couple of files I'd added, committed, but later realized didn't need to be tracked. After adding those files to .gitignore, I was able to do this and untrack them perfectly.Homily
Tip: for example if you add *.config to your .gitignore, you can do git rm --cached *.config to stop tracking all *.config files.Mouthpart
Also note doing this will delete the files from other repos you push to, even though it stays on your system. If you're just ignoring changes to files and don't want to delete them from other user's repos try using git update-index --assume-unchanged file.nameMouthpart
IMO, this is the correct answer. Wiki answer works-kinda, but is awfully heavy-handed, especially given the question. (I'd fix the wiki, but I'm not sure how. "Soon!" ;)Avowed
@Avowed be extremely careful with this "solution". This will remove the file in the repo, and anyone who pulls this change will have the file removed too. The best solution would be to assume-unchanged, as @Mouthpart said, or --skip-worktree as an alternative.Furcula
D
90

Yes - .gitignore system only ignores files not currently under version control from git.

I.e. if you've already added a file called test.txt using git-add, then adding test.txt to .gitignore will still cause changes to test.txt to be tracked.

You would have to git rm test.txt first and commit that change. Only then will changes to test.txt be ignored.

Devest answered 18/7, 2009 at 8:15 Comment(4)
This isn't entirely true, it is possible to ignore changes in a tracked file... see my answer: https://mcmap.net/q/11541/-ignore-files-that-have-already-been-committed-to-a-git-repository-duplicateEpiblast
git update-index --assume-unchanged <file> and git rm --caheced <file> was not actually working for me. I have done git rm <file> and then created new file after that <file> is successfully ignored. I am using git version 1.8.1 -- If that was the issue.Tonguetied
your syntax is wrong here. it's git rm test.txt and here's a link to a more comprehensive answer #12661806Gaither
This is the correct answer if your .gitignore is not working for some specific files. The accepted answer will cause a commit for all of your files.Nickname
A
57

Remove trailing whitespace in .gitignore

Also, make sure you have no trailing whitespace in your .gitignore. I got to this question because I was searching for an answer, then I had a funny feeling I should open the editor instead of just cat'ing .gitignore. Removed a single extra space from the end and poof it works now :)

Ashmead answered 2/2, 2012 at 15:59 Comment(4)
I had exactly the same problem, :P. I also got to this question because of that. Good thing you have this documented here. +1Downstate
If like me you use vi to quickly edit .gitignore use ':set list' to show whitespace.Ratel
This happenened to me when I did a echo node_modules >> .gitignore (at least on windows)Jerriejerrilee
For weeks I was frustrated with this until I saw your whitespace post. Thanks, fixed my problem.Payment
O
51

I followed these steps

git rm -r --cached .
git add .
git reset HEAD

After that, git delete all files (*.swp in my case) that should be ignoring.

Outbrave answered 15/7, 2011 at 7:22 Comment(2)
be careful with that one, as it assumes you want to add all files except what's ignored, and usually that's not the caseDowne
Awesomeness! +1Baumbaugh
H
44

Complex answers everywhere!

Just use the following

git rm -r --cached .

It will remove the files you are trying to ignore from the origin and not from the master on your computer!

After that just commit and push!

Hargrave answered 19/7, 2017 at 5:38 Comment(1)
This was only half of the solution. Also needed a 2nd command: git add . Credit to: dylanwooters.wordpress.com/2015/10/24/…Kannan
B
43

If you want to stop tracking file without deleting the file from your local system, which I prefer for ignoring config/database.yml file. Simply try:

git rm --cached config/database.yml
# this will delete your file from git history but not from your local system.

now, add this file to .gitignore file and commit the changes. And from now on, any changes made to config/database.yml will not get tracked by git.

$ echo config/database.yml >> .gitignore
Boxing answered 2/3, 2014 at 9:0 Comment(0)
U
31

To remove just a few specific files from being tracked:

git update-index --assume-unchanged path/to/file

If ever you want to start tracking it again:

git update-index --no-assume-unchanged path/to/file                      
Uppercase answered 21/8, 2013 at 14:20 Comment(0)
M
29

As dav_i says, in order to keep the file in repo and yet removing it from changes without creating an extra commit you can use:

git update-index --assume-unchanged filename
Maxfield answered 17/4, 2015 at 7:21 Comment(2)
Undo : git update-index --no-assume-unchanged filenameGranada
what if you want to do that for all files in a folder in one go?Acidic
M
28
  1. Move the file out of the git-controlled directory
  2. Check the removal into git
  3. Move the file back into the git-controlled directory

After moving the file back, git will ignore it.

Works with directories too!

Monoploid answered 15/11, 2015 at 4:3 Comment(0)
U
25

Not knowing quite what the 'answer' command did, I ran it, much to my dismay. It recursively removes every file from your git repo.

Stackoverflow to the rescue... How to revert a "git rm -r ."?

git reset HEAD

Did the trick, since I had uncommitted local files that I didn't want to overwrite.

Uxoricide answered 12/4, 2011 at 20:39 Comment(2)
The git rm -r --cached . didn't work for me. Git was still claiming an my textmate project file was not being tracked even though .tmproj is in my global ignore file. Resetting my local repro like this worked, though. Actually I added the 'hard' option as in git reset --hard HEAD. That should have nearly the same effect in this case.Faust
Be careful with the --hard flag. It will throw out any uncommitted changes without a warning!Offensive
S
25

Put the .gitignore file into your repository root not in .git folder.

Smudge answered 18/6, 2013 at 21:8 Comment(0)
A
23

If the files are already in version control you need to remove them manually.

Akilahakili answered 16/7, 2009 at 19:28 Comment(2)
I tried git rm --cached and git reset HEAD both tools I'm fairly familiar with and just could get it from the repo. Success came from first rm --cached, then actually manually deleting it, committing the delete, then recreating it manually. And it's gone.Trillion
This worked for me like so: rm foo/bar && git add -u && git commit -m "removed foo/bar" && git push. Then running touch foo/bar && git status will show the file is now properly ignored.Sailor
D
21

Another problem I had was I placed an inline comment.

tmp/*   # ignore my tmp folder (this doesn't work)

This works

# ignore my tmp folder
tmp/
Dylan answered 6/12, 2011 at 13:14 Comment(0)
T
16

Thanks to your answer, I was able to write this little one-liner to improve it. I ran it on my .gitignore and repo, and had no issues, but if anybody sees any glaring problems, please comment. This should git rm -r --cached from .gitignore:

cat $(git rev-parse --show-toplevel)/.gitIgnore | sed "s/\/$//" | grep -v "^#" | xargs -L 1 -I {} find $(git rev-parse --show-toplevel) -name "{}" | xargs -L 1 git rm -r --cached

Note that you'll get a lot of fatal: pathspec '<pathspec>' did not match any files. That's just for the files which haven't been modified.

Taimi answered 3/7, 2012 at 17:25 Comment(1)
Is the sed s//$// supposed to be s/$//? Also, what's the point of the sed and grep commands? I'm guessing it's comment filtering from the gitignore?Tarim
I
11

I have found a weird problem with .gitignore. Everything was in place and seemed correct. The only reason why my .gitignore was "ignored" was, that the line-ending was in Mac-Format (\r). So after saving the file with the correct line-ending (in vi using :set ff=unix) everything worked like a charm!

Interstratify answered 2/3, 2012 at 9:56 Comment(2)
If anyone has problems with .gitignore after creating the file in windows notepad, there is more information here: https://mcmap.net/q/11783/-gitignore-is-ignored-by-git/…Shuster
The .gitignore format is each line is either a comment (starting with a #) or the whole line (including any whitespace) is full filename pattern. If you have \r mixed into the line, git will ignore only files that end up with \r (you can create those if you want!). See man gitignore for details, it's worth reading.Offensive
S
10

One other problem not mentioned here is if you've created your .gitignore in Windows notepad it can look like gibberish on other platforms as I found out. The key is to make sure you the encoding is set to ANSI in notepad, (or make the file on linux as I did).

From my answer here: https://mcmap.net/q/11783/-gitignore-is-ignored-by-git

Shuster answered 21/5, 2013 at 9:43 Comment(0)
K
9

If you need to stop tracking a lot of ignored files, you can combine some commands:

git ls-files -i --exclude-standard | xargs -L1 git rm --cached

This would stop tracking the ignored files. If you want to actually remove files from filesystem, do not use the --cached option. You can also specify a folder to limit the search, such as:

git ls-files -i --exclude-standard -- ${FOLDER} | xargs -L1 git rm

Keir answered 20/4, 2017 at 6:18 Comment(1)
This should be the accepted answer. git rm -r --cached . removes lot of other things!Moersch
M
8

On my server linux server (not true on my local dev mac), directories are ignored as long as I don't add an asterisk:

www/archives/*

Molarity answered 9/3, 2013 at 6:36 Comment(0)
A
8

One thing to also keep in mind if .gitignore does not seem to be ignoring untracked files is that you should not have comments on the same line as the ignores. So this is okay

# ignore all foo.txt, foo.markdown, foo.dat, etc.
foo*

But this will not work:

foo*   # ignore all foo.txt, foo.markdown, foo.dat, etc.

.gitignore interprets the latter case as "ignore files named "foo* # ignore all foo.txt, foo.markdown, foo.dat, etc.", which, of course, you don't have.

Acuate answered 19/2, 2016 at 22:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.