Change a Git Commit History
There might be instances where you have to change a commit to an earlier date, whether it's to maintain consistency in your commit history or for particular reasons related to managing branches. This could involve modifying both the author information and the commit message to accurately reflect these changes.
Most recent Commit
git commit --amend --no-edit --date <date> --author <author> -m <message>
Where:
- date: new commit date for the commit
- author: new commit author in 'Jane Smith jane.smith@example.com' format
- message: new commit message
For example, the following command will set the commit date to Jan 31, 2023 at 2.30 pm UTC
.
git commit --amend --no-edit --date 2023-01-31T14:30:00Z
Other Commits
To be able to edit in date for more older commits, we need to use git rebase
.
Start Interactive Rebase
git rebase -i HEAD~<N>
Where:
- N: a commit before the commit you want to modify
Select Commit Git rebase will open a text edit. You can choose the commit you want to edit by changing
pick
toedit
next to the commit.edit <commit_hash> <commit_message>
Amend Commit
Upon saving and exiting the editor, Git will pause the rebase operation at the specified commit. Modify the commit date using:
git commit --amend --no-edit --date <date>
Continue Rebase
git rebase --continue
Repeat steps 3 and 4 if you selected multiple commits.
Force Push
git push --force
Example
The following sequence of commands will:
- Rebase
5
commits back fromHEAD
. - Choose to commits
- Modify date for commit
a0b1c22
, and continue rebase - Modify date for commit
a0b1c24
, and continue rebase
When you are done you can push the changes, remember you will need to force the changes.
git rebase -i HEAD~5
pick a0b1c25 message 5
edit a0b1c24 message 4
pick a0b1c23 message 3
edit a0b1c22 message 2
pick a0b1c21 message 1
git commit --amend --no-edit --date 2023-01-31T14:30:00Z
git rebase --continue
git commit --amend --no-edit --date 2023-02-01T10:15:00Z
git rebase --continue