Organize your commits like a pro with git rebase and git commit --amend
If you work by yourself, git commit messages may seem unimportant and we can create as many commits as we want and can write commit messages in any way we like. Eventually, we may end up having a large number of small commits with only short commit titles.
It is OK if you will never publish your git repository publicly. However, if you want to showcase your repository to an interviewer, you’d better organize your commits in a more professional way. Moreover, if you work in a team and push some commits to your in-house repository, you will be required to organize your commits properly.
In this article, I will introduce two commands, namely
git commit --amend , and
git rebase --interactive , which can be used to organize your commits in a professional way.
We can use
git commit --amend to modify the last commit of the current branch, which is normally called HEAD. If we run
git commit --amend directly, only the commit message will be updated and file changes will not be impacted. If some files are updated after the last commit was created and need to be added to the last commit, we should add those files before we run
git commit --amend.
It is very important to note that if you run the
git commit --amend command, no matter whether you modify the commit message or not, the commit id will always be updated, which means the original commit will be discarded and a new commit will be created.
$ git log --oneline
f73b1e9 (HEAD -> git-demo-rebase) Update$ git commit --amend$ git log --oneline
bd28027 (HEAD -> git-demo-rebase) Update
If you haven’t pushed your original commit yet, it won’t cause any problem. However, if you have already pushed the original commit to the remote repository, you will need to use
git push -f to push the amended commit. Alternatively, you can delete the last commit in the remote repo with this command: