This guide explains how to modify or combine commits that have already been created. These are powerful tools for keeping your Git history clean and readable.
—
This is the perfect tool when you've made a mistake in the message of your most recent commit.
Run the following command. This will open your default text editor to let you change the message.
git commit --amend
Alternatively, to change the message directly from the command line without opening the editor:
git commit --amend -m "feat(auth): [JIRA-123] Add user login endpoint"
Because you have changed a commit that already exists on the remote server, you must force the update. Always use the safer `–force-with-lease` option.
git push --force-with-lease origin <your-branch-name>
--force-with-lease
flag is safer than
--force
because it checks if another person has pushed new commits to the branch in the meantime. If they have, the push will fail, preventing you from accidentally overwriting their work.
—
“Squashing” means to combine several smaller, sequential commits into a single, logical commit.
We will use the interactive rebase command (
git rebase -i
).
If you want to combine the last 3 commits, run the following command:
git rebase -i HEAD~3
(Replace `3` with the number of commits you want to work with).
A text editor will open with a list of the commits you selected, with the oldest one first.
pick 1a2b3c4 feat: Add initial login form structure pick 5d6e7f8 fix: Correct validation logic on login pick 9g8h7i6 refactor: Clean up login service
To combine them, keep the first commit with **<code>pick</code>** and change the action for all subsequent commits to **<code>squash</code>** (or the shorthand **<code>s</code>**).
pick 1a2b3c4 feat: Add initial login form structure s 5d6e7f8 fix: Correct validation logic on login s 9g8h7i6 refactor: Clean up login service
Now, save and exit the editor.
Git will open another text editor, containing the messages from all the commits you are squashing. Delete the old text and write a single, clear message that describes the combined change.
feat(auth): [JIRA-123] Implement user login functionality - Adds the HTML structure and styling for the login form. - Implements client-side and server-side validation for user credentials. - Refactors the authentication service for better clarity and performance.
Save and exit the editor.
Your local history has now been rewritten. Update the remote server using the safe force-push command:
git push --force-with-lease origin <your-branch-name>