I want to fix a file in past commit. This might affect all ascending commits.
Is there an easy way to do that?
Many times when I commit twice I find that I've had error in the first commit, and I wish to fix the error without having to git reset
my last good commit.
For clarification, I want to change the actual commit, that is, I want the content of the past commit to be changed. In other words, I want to change history!
You can modify the most recent commit in the same branch by running git commit --amend. This command is convenient for adding new or updated files to the previous commit. It is also a simple way to edit or add comments to the previous commit. Use git commit --amend to modify the most recent commit.
Changing the latest Git commit message If the message to be changed is for the latest commit to the repository, then the following commands are to be executed: git commit --amend -m "New message" git push --force repository-name branch-name.
If you only want to amend the second to last commit (eg. not long ago, especially not before many branches and merges), then I use this procedure:
git checkout -b tmp bad-commit
git commit --amend
git rebase tmp master
If you have merges in between, you may wanna try rebase -i -p
, but the results may vary.
It looks like:
filter-branch
(complex command which could do what you want)You can find an example of rebase interactive in this comment: you could then avoid the temporary branch, but again, it is more complex.
I also rebase often to clean up the history of development so that changes are correct and grouped properly.
A made-up example:
I rename functionfoo
tobar
and commit it with a comment that says, "renamed foo to bar".
Then I move on to the next feature or fix, and commit that, and move on to the next.
Halfway through that, I find that I missed an instance offoo
!
I commit my work in progress (or use git-stash), fix the missing 'foo' and commit that, then usegit-rebase --interactive
to merge the all thefoo
fixes together into one clean commit.
If I didn't usegit-stash
, then I'll usegit-commit --amend
(another form of rebasing) when I finally finish the feature that was in progress.When my patches are pushed for review, all the pieces are correct and tell a coherent story. Sometimes I use
git-rebase --interactive
just to make adjacent temporally-separated changes which affect the same bits, so that changes are in context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With