Note: you will need a clean working directory to do this.
We will be rewriting history! This will entirely remove the commit from history
You should probably only do this if you really need to remove a file entirely from history. For example if the file you added is too large and GitHub won't accept it. If you are just trying to undo what a commit has done, there are better ways to do it without modifying history, check out git revert.
We are assuming that the problematic file was added in one commit and not modified since.
-
find the sha of the commit that introduced the bad file
# will display the hash of the commit where the file was introduced git log --pretty='%H' problematic-file.jpg | tail -n 1
replace
problematic-file.jpgwith the file that you want to remove from history.copy down that hash
-
get rid of that commit
git rebase --onto <hash>^ <hash> HEAD
Replacing
<hash>with the commit you coppied in the previous stepNote that we will paste the hash twice, the first time with a
^after it -
create a new branch based off of where we are and switch to it
The previous command will leave us in a detached HEAD state, so we'll need to create a branch based off of our current state.
git branch branch-without-problematic-file git checkout branch-without-problematic-file
-
do a
git logto verify that the problematic file is not longer in your commit historygit log -
delete the old master branch as it still contains the problematic file
Note: replace master with the branch you are working from if it's different than master
at this point we should be in our
branch-without-problematic-filebranchgit branch -D master -
rename our branch to master
git branch -m master
Now we will have removed the problem file from our commit history!
# from 'my-branch' remove 'problem.file' from 'my-branch's history entirely
for commit in $(git log --pretty='%H' problem.file); do git rebase --onto $commit^ $commit my-branch; done