28

I've made some commits and have pushed it to my remote repo. One of those I want to remove. It includes only one binary file, which was changed only in that commit in that branch. How to remove it without harm for later commits?

Russiancold
  • 1,179
  • 1
  • 11
  • 26
  • 6
    `git rebase -i TARGET_COMMIT~1` and then don't pick `TARGET_COMMIT` I think would work. – CollinD Feb 28 '17 at 20:28
  • 1
    In @CollinD solution, you will have to force your push to remote repository (preferred `--force-with-lease`), because your changes won't be possible to fast-forward. If you want to avoid those issues, you can `git revert` this commit. – kolejnik Feb 28 '17 at 21:12

3 Answers3

56

You can use interactive (-i) rebase to remove a previous commit.

$ git log                          # copy the target commit 

$ git rebase -i <target-commit>~1  # start rebase from the previous commit of target commit

An editor will open with a list of commits, one per line. Each of these lines begins with pick. Comment out your target commit's line (Put # at the start of target commit line).

OR, put drop or d instead of commenting out the line with #.

$ git rebase --continue      # repeat the command until finish rebase

Now, you need to do force (-f) push to remote since git history has been changed!

$ git push -f origin HEAD 
Sajib Khan
  • 22,878
  • 9
  • 63
  • 73
6

The flag --rebase-merges should be considered in answer, because the accepted solution will remove the merge commit between HEAD and target commit~1

Example:

Before any rebase:

f3e07b4 (HEAD -> dev, origin/dev) headCommit
dd3d182 Merged PR 425: added playoutServerUsage
7ed3eb5 added playoutServerUsage
03b52af feat: add Description Series  #targetCommit
0a1217c some_older_commit

git rebase -i target-commit~1

c11fa07 (HEAD -> dev) headCommit
7ed3eb5 added playoutServerUsage
0a1217c some_older_commit

git rebase -i target-commit~1 --rebase-merge

a1943b6 (HEAD -> dev) headCommit
12411a1 Merged PR 425: added playoutServerUsage
7ed3eb5 added playoutServerUsage
0a1217c some_older_commit

Rebase with flag --rebase-merges can be harder and whole process will be longer (bigger tree), but still we have to locate target commit and change 'pick' to 'drop'

After that, I would recommend using

git push --force-with-lease origin HEAD 

instead of force only.

force vs force-with-lease

PS. It is worth paying attention to which commits hashes was changed

Adi Prasetyo
  • 1,006
  • 1
  • 15
  • 41
KJanek
  • 147
  • 1
  • 11
-3

If untracking all the files is okay with you, then you can try deleting the .git file from the directory.
This files contains all the details regarding all the git commits.

It worked for me and may also work for you.

Mr. Techie
  • 622
  • 7
  • 17