How to go back to an old commit, make some changes and commit those changes at the old commit which also updates all the following commits

I was working on a file, I comitted some changes, then I realized that I want some of the changes I've made recently in an older commit, because it is a part of the older commit.

So, I want to go back to the commit 2c57de7 and add some of the changes that I've still not added to the staging area, in the same commit. I do not want to create a new commit.

  • I tried the Detached HEAD state, but then I don't know how to merge a branch after the 2c57de7 commit.
  • I tried the interactive rebase option by stashing my current work and the popping the work at the 2c57de7 commit and the resetting the commit so I could add the modified file. But I'm having a lot of merge conflicts. If there's an article about how to resolve merge conflicts, it would be extremely helpful!
  • I tried making a new branch, reverting that branch to that old commit, making the changes, and then merging the tip of that branch back, but it didn't work.
* 59939c3 - Sun, 16 Jan 2022 14:19:40 +0530 (3 hours ago) (HEAD -> main)
|           Problems - Added Problem 03
* 2c57de7 - Sun, 16 Jan 2022 12:52:04 +0530 (4 hours ago)
|           Problems - Added Problem 02
| * 3031e71 - Sun, 16 Jan 2022 13:37:14 +0530 (3 hours ago) (Trees)
| |           Level Wise
| * 7aaa1dd - Sun, 16 Jan 2022 12:44:59 +0530 (4 hours ago)
| |           Introduction
| * 5c26db8 - Sat, 15 Jan 2022 18:13:23 +0530 (23 hours ago)
|/            Vectors
* 692c42e - Wed, 12 Jan 2022 19:10:02 +0530 (4 days ago)
|           Problems - Added Problem 01

This is my commit history

Any help would be appreciated!


Solution 1:

which also updates all the following commits

That means you would need to rebase those following commits on top of your updated old commit.

From your current main:

git branch tmp
git stash
git switch -C main 2c57de7  # reset main back to 2c57de7 
git stash pop
git add .
git commit --amend -m "Problems - Added Problem 02, amended"
git switch tmp
git rebase main
git switch main
git merge tmp
git branch -d tmp