Can you change the commit history?
Why history can be changed at all
Git is a distributed system. The commit history is not something "sacred," it is just a chain of objects, and Git allows you to:
- rewrite commits
- delete them
- combine them
- change the message and the author
As long as commits have not reached a shared repository, you are free to do whatever you want with them.
How history can be changed (main ways)
1. git commit --amend
Used to change the last commit:
- fix the message
- add a forgotten file
git commit --amendThis rewrites the last commit, creating a new one.
2. git rebase (especially interactive)
The most powerful tool for changing history.
It lets you:
- change commit messages
- combine commits (squash)
- change the order
- delete commits
git rebase -i HEAD~3Interviewers really like this one, as a sign of solid Git knowledge.
3. git reset
Lets you move the branch pointer back:
--soft--mixed--hard
For example:
git reset --hard HEAD~1Can delete commits if nothing else references them.
4. git revert (an important difference!)
git revert does not change the history, it adds a new commit that undoes the changes of the old one.
This is a safe way for public branches.
The main rule (the key point for an interview)
You cannot rewrite history that is already used by others.
A phrasing interviewers really like:
History can safely be changed only on local or not-yet-published branches.
Why this is dangerous in a shared repository
If you changed the history and did push --force:
- your colleagues' history breaks
- conflicts appear
- you can lose someone else's work
Short answer for an interview
Yes, the commit history in Git can be changed, using
commit --amend,rebase,reset. But it is safe only for local or unshared commits. On public branches, history is not rewritten,git revertis used instead.
A common candidate mistake
"You can't change history in Git" "You always can, if you're careful" You can, but with a clear understanding of the context and the consequences
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.