Om3ga
Om3ga

Reputation: 32853

How to remove a file from git branch

I committed, but not pushed to repository, a file to a branch i.e. abc. Now I want to remove it from this branch abc. How can I achieve this?

Upvotes: 5

Views: 3412

Answers (1)

Stephen Jennings
Stephen Jennings

Reputation: 13234

I'm assuming you want to obliterate the file from history, as if it never existed. If you just want to get rid of the file in future commits, then use git rm my-bad-file.txt and ignore the rest of my answer.


If the file is only in your most recent commit, then it's easiest to use git rm my-bad-file.txt to remove the file, then git commit --amend to edit the previous commit.

If there are several commits containing the offending file, then git filter-branch might be useful.

git filter-branch --index-filter 'git rm --cached --ignore-unmatch my-bad-file.txt' master..abc

This means:

  • git filter-branch: Let's rewrite some commits!

  • --index-filter: Change each commit's index without actually checking it out on disk.

  • 'git rm --cached --ignore-unmatch my-bad-file.txt': For each commit, unstage the file named "my-bad-file.txt" if it exists.

  • master..abc: Do this on all commits on branch abc back to where it forked from the master branch.

Upvotes: 9

Related Questions