Reverting While Keeping Changes with --no-commit
Sometimes, you want to undo the changes from a commit but keep them in your working directory to modify them. For example, you might want to fix a mistake in the commit rather than discarding it entirely. The --no-commit (or -n) option is perfect for this.
First, let's reset our repository to the state before our last revert, so we can try a different approach. We will use git reset for this. This command moves the HEAD pointer, and --hard updates the files in your working directory to match.
git reset --hard HEAD~1
This command removes the "Revert" commit we just made. You can confirm this by running git log --oneline.
Now, let's revert the "unwanted" commit again, but this time using the --no-commit option. Remember to use the hash for the "Add a second, unwanted line" commit.
Please replace <your-commit-hash> with the actual hash from your terminal.
git revert --no-commit <your-commit-hash>
This time, no editor pops up. The revert is prepared, but not committed. Check the status of your repository:
git status
The output will show that story.txt is staged for commit:
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: story.txt
The changes from the reverted commit are now in your staging area. You can now modify them. Let's replace the unwanted line with a better one. Open story.txt with nano:
nano story.txt
The file will look like it did after the revert in Step 2. Add a new, better line to the end of the file:
And they lived happily ever after.
Save and exit nano (Ctrl+O, Enter, Ctrl+X).
Now, add your changes to the staging area and commit them with a new, descriptive message:
git add story.txt
git commit -m "Replace unwanted line with a proper conclusion"
Finally, check the log and the file content to see the result:
git log --oneline
cat story.txt
The log shows your new commit, and story.txt has the corrected content. You have successfully reverted a commit while preserving and modifying its changes.