Skip to content

Instantly share code, notes, and snippets.

@nivethan-me
Last active October 15, 2023 05:55
Show Gist options
  • Save nivethan-me/a4b798ab0a1184a43c0528a689034026 to your computer and use it in GitHub Desktop.
Save nivethan-me/a4b798ab0a1184a43c0528a689034026 to your computer and use it in GitHub Desktop.
Add files to an old commit in Git

Add files to an old commit in Git

Scenario

I made three commits in a project locally and realized I should have added a pnpm-lock.yaml file into the first commit.

Using git rebase to solve the issue

1. Start interactive rebase with last 3 commits. ``` git rebase -i HEAD~3 ``` This opens an interactive rebase window listing the last three commits.
  1. Edit the Commits: An editor will open showing something like following
pick abc123 feat(client): project init
pick def456 feat(client): only allow pnpm as package manager
pick def456 feat(client): add .nvmrc file to ensure the project runs with the correct Node version

Change pick to edit for the commit you want to edit. like following

edit abc123 feat(client): project init
pick def456 feat(client): only allow pnpm as package manager
pick def456 feat(client): add .nvmrc file to ensure the project runs with the correct Node version

save and close the file.

  1. Amend the file to the picked commit. Now you're time travelled to the first commit (you can confirm this by git log --oneline as you can see only your first commit) add the missed file & amend the commit
git add pnpm-lock.yaml
git commit --amend

save and close the file.

  1. Finish the rebase use the following command to finish the rebase and come back to the present commits
git rebase --continue

Now your changes are successfully added to the first commit, and your commit history is revised.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment