The commits probably aren't lost. Make a backup first. Check what branches you have, and what's in them. You might be interested to learn about the reflog, if you really can't find your commits in any branch.
If you don't have a repository browser installed (I like tig), you could inspect your repository using a command like this: git log --graph --all --oneline --decorate
How do I edit a previous commit and submit it without erasing the commits ahead of it on the master?
If the commit to edit is the previous commit:
- Make the changes you want.
- Stage the changes, probably using
git add -u
if you're not adding new files. - Amend the previous commit,
git commit --amend
will do that, add-C HEAD
if you don't want to edit the commit message.
If you want to edit an older commit, you need to use rebase. This can be done interactively:
- Start from whichever branch you want to edit, usually with no changes in your working copy.
- Make the changes you wanted in the earlier commit.
- Stage and commit those changes - don't bother writing a sensible commit message here.
- Run
git rebase -i
, this will open an editor:- Move the last line (with the nonsense commit message) up until it is on the line below the commit you want to edit.
- Change
pick
at the start of the line tof
(for fixup). - Make no other changes to the file
- Save and exit
- Git should modify your earlier commit to include the edit, and will try to rebase your other changes on top.
This will try to apply your edits to the earlier commit, and rebase all your subsequent changes on top of the earlier commit plus your edits. You might get merge conflicts if the later commits are affected by your edit. Git will provide instructions on how to resolve these. If you don't understand them, you can use git rebase --abort
to go back to where you started, with your edits being the latest commit.
Note that you should not edit commits that you have already pushed to a shared repository. This is likely to create a lot of confusion.