To add files to an existing commit in Git, you need to follow these steps:
- Make sure you are on the branch where the commit was made. You can check your current branch with the command
git branch
. - Make changes to the files you want to add to the commit.
- Stage the changes with the command
git add <file>
. You can add one or more files by separating them with spaces, or add all changed files with the commandgit add .
. - Use the command
git commit --amend
to amend the previous commit. This will open a text editor where you can modify the commit message. Alternatively, you can use the option-m
followed by the new commit message to specify the message inline:git commit --amend -m "New commit message"
. - Save and close the text editor to finalize the commit.
Note that amending a commit will replace the old commit with the new one, and the commit hash will change. This means that if you have already pushed the old commit to a remote repository, you will need to force push the new commit to overwrite the old one with the command git push --force
.
git commit --amend -m "New commit message"
.git push --force // only if you already pused commit
Also, keep in mind that it’s generally not recommended to amend commits that have already been pushed to a remote repository, as it can cause confusion and conflicts with other team members.