Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git Ignore not working, I don't get it

I thought I had figured this out but on recent attempts it is failing.

I need to commit a file, then after the commit ignore it on any subsequent repo commits.

Lets say the file is example.txt.

I commit changes to example.txt and push them to github.

I then touch .gitignore and add example.txt to it and save.
I then use git rm --cached example.txt
Then git add .gitignore to commit -->push it

The problem at this step is a git status is showing example.txt as deleted and thus the commit/push deletes it from the remote repo.

I have tried several variations on creating a .gitignore and rm --cached, and it either deleted the file or does not ignore it and commits unwanted changes.

Looking for insight on the exact process to ignore already committed files without deleting them.

like image 875
Wyck Avatar asked Dec 21 '25 05:12

Wyck


2 Answers

You do realize that git rm --cached example.txt will remove the file from the index and keep it in the working directory alone. And then when you commit, your are committing the the deletion of the file, in addition to the .gitignore file that you added. Thus, when you push the file, it will be deleted from the repo.

Also, you cannot ignore changes to a tracked file using gitignore. You can instead try to do git update-index --assume-unchanged example.txt to "ignore" the file.

like image 168
manojlds Avatar answered Dec 24 '25 05:12

manojlds


One possible approach is to tell Git to assume the file is unchanged.

$ mkdir project
$ cd project
$ touch example.txt
$ git init
$ git add .
$ git commit -m "checkin..."
$ git update-index --assume-unchanged example.txt
$ echo "hello" >> example.txt
$ git status
# On branch master
nothing to commit (working directory clean)
$

Trust that's what you want. Be forewarned that this approach has its warts -- especially if you try to switch to a branch where the version of example.txt is different from what's in master.

like image 24
Sri Sankaran Avatar answered Dec 24 '25 04:12

Sri Sankaran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!