KPK
KPK

Reputation: 442

Unable to unstage git committed file

When we added a directory to git, we had some temporary files (ending in .~) that we don't want to track added already by mistake.

We've since setup a .gitignore file with a *.~ rule. This works for all new temporary files, but we're unable to remove the few that were already committed.

When we run git rm --cached <file> it moves the file from modified: to a deleted: status. And says

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       deleted:    FILE.~

But when we run git reset HEAD FILE.~, it's still in the list of files under

Unstaged changes after reset:
M       pd/FILE.~

Upvotes: 3

Views: 2711

Answers (2)

Learath2
Learath2

Reputation: 21383

The problem is that stage is not what you think it is File Lifecycle

Above image from the Git Book clearly shows the file statuses.

The temporary files you already commited are not actually staged but they are tracked. Git stops tracking files when commit a remove. git status says there is a change to be commited which is removing the file. git commmit -a -m "Removed temp files" should actually commit the remove and make the file untracked.

However, this won't remove the file from older commits for which I like to link people to Github Help: Remove Sensitive Data as it explains it very clearly.

git filter-branch --force --index-filter \ 'git rm --cached --ignore-unmatch ' \ --prune-empty --tag-name-filter cat -- --all

Above command will also purge the old files from history completely which you probably don't need but I included as extra information.

Upvotes: 2

Andrew Aylett
Andrew Aylett

Reputation: 40750

You're almost there: stop after step one and commit!

The message given by git status is how to undo the change you've already made, if you made it in error. You've done the right thing in running git rm --cached <file> -- that command removes the file from your staging area, while leaving it present in your local copy. Git status tries to be helpful, by letting you know what you need to do if a file has an incorrect status. In this case, the file has the correct status so you can go ahead and commit.

Upvotes: 3

Related Questions