Skip to main content

Edit a Commit

Edit a commit (latest or old) to insert something extra and safely push

NOTE: As a thumb rule it's recommended to edit commits on you own branch, if someone else is co-working on the same branch, then do these with caution.

Add a change to the last commit

  1. Make your code changes:
nano path/to/file
  1. Check what changed:
git status
git diff <file_path>
  1. Stage the changes:
git add path/to/file
  1. Replace/update the latest commit while keeping its message:
git commit --amend --no-edit

To edit the commit message, use:

git commit --amend -m "new commit message"

  1. Verify the amended commit:
git status
git log --oneline --decorate -5
  1. Confirm exactly what differs from the remote

  2. Safely overwrite the remote version of the amended commit:

git push --force-with-lease origin branch-name

Why --force-with-lease: If a coworker pushes new commits to the same remote branch while you are working, a standard --force push will blindly overwrite and permanently erase their changes.

  1. Check the remote to see new changes

Editing an Older (Deep) Commit

  1. Start an interactive rebase counting back the number of commits (eg: last 3 commits):
git rebase -i HEAD~3

This will open an editor like Nano

  1. Change the word pick to edit next to the target commit.

  2. Save and exit the editor

  3. Do your file changes, then run:

4.1. Stage the changes:

git add <file>

4.2. Incorporate the changes into the older commit:

git commit --amend

4.3. Complete the rebase process:

git rebase --continue

4.4. Push the changes to remote

git push --force-with-lease origin branch-name

Already edited, not commited, add to older commit

  1. Stash your current uncommitted changes:
git stash
  1. Follow the step in Editing an Older (Deep) Commit from 1 to 3

  2. Pop your stashed changes back:

If the stashed item was the last in.

git stash pop

If there more stashes on top of stash you required, then use git stash list to get the number of stash, which look like stash@{2} then the command will be like git stash pop stash@{2}.

  1. Stage the changes:
git add <file>
  1. Incorporate the changes into the older commit:
git commit --amend --no-edit
  1. Complete the rebase process:
git rebase --continue
  1. Push the changes to remote (now the hash of commit in local and remote is changed)
git push --force-with-lease origin branch-name