2

How I can modify the second last pushed commit using GIT, I need to delete some files from the mentioned commit, and I would like to preserve the last commit.

What I did so far:

git reset --soft HEAD^
git reset --soft HEAD^   # two times

git reset HEAD .idea/  # and the same for other directories

git add -A
git commit --amend
Niket Pathak
  • 6,323
  • 1
  • 39
  • 51

1 Answers1

2

What you need to do is a rebase to the commit you want to modify.

Steps:

  1. Get the commit ID of the commit you want to modify.

    git log -2 // here '2' => will display last 2 commits
    // lets say the commit you wish to change has ID "ededeac"
    
  2. Do an interactive Rebase

    git rebase --interactive ededeac // where "ededeac" is the commit to modify
    

    An editor will come up, with a list of all commits since the one you gave. Change pick to edit for the commit needed to be modified.

    pick 8c27d78 fixed some bug
    edit ededeac fixed another bug // here, we changed pick to edit
    

    Save and exit. Git will then replay the listed commits.

    For each commit you want to edit, Git drops you into the shell. Then you can change the commit in any way you like.

    // delete/update files
    git commit --all --amend //here you can change the commit message too
    // The new changes are added on to the old commit
    // You can verify that with 'git log' and 'git diff HEAD^'
    git rebase --continue
    
  3. Force Push to origin.

    git push origin --force-with-lease
    

    You need to force push to the origin since you are rewriting history.

Niket Pathak
  • 6,323
  • 1
  • 39
  • 51
  • in the second step : `git rebase --interactive "hash of the 2 commit" ` in the editor I got only one commit (which corresponds to the first commit, the second is not existing ) `pick 8c27d78 blabla` – Jaouhar Mbarek Mar 17 '17 at 15:52
  • @JaouharMbarek that's because you probably selected an incorrect commit ID. try `git log -10` to see your last 10 commits, then try again with the desired commit ID. – Niket Pathak Mar 17 '17 at 16:16