Being in branch B, I realized I need to fix commit that exists in both branches A and B. Here what I tried to do, but with no result (only fourth commit's hash changes):
#!/bin/bash -eu
rm -rf 1
mkdir 1
cd 1
git init
echo 1 >1
git add .
git commit -am 1
echo 2 >2
git add .
git commit -am 2
echo 3 >3
git add .
git commit -am 3
git checkout -b B
echo 22 >2
git add .
git commit -am 2
git rebase -i HEAD~3 # fix second commit with fourth one, like this:
# pick 485dacc 2
# f 976dc2a 2
# pick d899817 3
git rebase master || true
echo 22 >2
git add .
git rebase --continue