git – How to exclude files from a commit to include them in another

Question:

Is it possible to go back to the state before the commit and do it differently, or how to exclude files from the commit in order to include those files in another commit?

Answer:

Yes, you can fix the old commit like this:

  • create a branch on the commit being fixed, checkout -b it ( checkout -b )
  • fix the code, fill in the commit (but!) with the ammend last commit option (there is such a switch in the UI, and a parameter on the command line)
  • all commits from the old branch after the fixed one are moved to the new branch ( rebase – move at once, or cherry-pick – one at a time). I prefer one at a time for better conflict resolution. cherry-pick can also be done from the UI – right-click on the commit – and there will be such an option.

If you want to exclude files from it – at the stage of editing the code – remove them from the commit – "hide" with the command git stash save , ammend last commit to ammend last commit current one, cherry-pick to the desired commit where you want to insert the files and use the git stash pop command git stash pop them out of the cache and commit them properly.

Scroll to Top