What to Do When You Forget to Add a File to a Git Commit
If you've ever committed changes in Git and realized you forgot to include a file, don't worry, you're not alone.
Fortunately, there's an easy way to fix this using Git's amend feature.
How to
First, you need to stage the file you forgot. This is done with the git add
command:
git add file-you-forgot.txt
Next, you'll amend your last commit to include the newly staged file. The git commit --amend
command will take the previous commit, undo it, and apply all the currently staged changes (including the forgotten file), then commit again.
git commit --amend
This command will open your default text editor, allowing you to keep or change the commit message. If you don't need to change the message, just save and close the editor.
Change the Commit Message (Optional):
If you want to change the commit message while adding the forgotten file, you can use the -m
option to specify a new message:
git commit --amend -m "New commit message"
Notes ⚠️
Using git commit --amend
is easy but has some caveats. It rewrites the commit history, so it should be used with caution:
- Only use this method on local branches that you haven't shared with others yet. Amending commits in shared branches can cause issues for other developers who might have already pulled the original commit.
- If you decide to amend a commit that's already been pushed to a shared repository, make sure no one else is working on the same branch.