I am trying to merge 2 commits into 1, so I followed “squashing commits with rebase” from git ready.
I ran
git rebase --interactive HEAD~2
In the resulting editor, I change pick
to squash
and then save-quit, but the rebase fails with the error
Cannot 'squash' without a previous commit
Now that my work tree has reached this state, I’m having trouble recovering.
The command git rebase --interactive HEAD~2
fails with:
Interactive rebase already started
and git rebase --continue
fails with
Cannot 'squash' without a previous commit
Best Answer
Summary
The error message
means you likely attempted to “squash downward.” Git always squashes a newer commit into an older commit or “upward” as viewed on the interactive rebase todo list, that is into a commit on a previous line. Changing the command on your todo list’s very first line to
squash
will always produce this error as there is nothing for the first commit to squash into.The Fix
First get back to where you started with
Say your history is
That is, a was the first commit, then b, and finally c. After committing c we decide to squash b and c together:
(Note: Running
git log
pipes its output into a pager,less
by default on most platforms. To quit the pager and return to your command prompt, press theq
key.)Running
git rebase --interactive HEAD~2
gives you an editor with(Notice that this todo list is in the reverse order as compared with the output of
git log
.)Changing b’s
pick
tosquash
will result in the error you saw, but if instead you squash c into b (newer commit into the older or “squashing upward”) by changing the todo list toand save-quitting your editor, you'll get another editor whose contents are
When you save and quit, the contents of the edited file become commit message of the new combined commit:
Note About Rewriting History
Interactive rebase rewrites history. Attempting to push to a remote that contains the old history will fail because it is not a fast-forward.
If the branch you rebased is a topic or feature branch in which you are working by yourself, no big deal. Pushing to another repository will require the
--force
option, or alternatively you may be able, depending on the remote repository’s permissions, to first delete the old branch and then push the rebased version. Examples of those commands that will potentially destroy work is outside the scope of this answer.Rewriting already-published history on a branch in which you are working with other people without very good reason such as leaking a password or other sensitive details forces work onto your collaborators and is antisocial and will annoy other developers. The “Recovering From an Upstream Rebase” section in the
git rebase
documentation explains, with added emphasis.