It’s too easy to lose work with git reset --hard
. Fortunately, there is a safer alternative: git reset --keep
.
git reset --keep
gives the same result as git reset --hard
but without deleting your uncommitted changes. Instead of losing your work, it gives you an error message.
Example
Create, Commit, and Modify a File
% touch file
% git add file
% git commit -m "Create a file"
% echo "content" >> file
% git add -u
% git commit -m "Add content to the file"
% echo "more content" >> file
% git status
On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: file
no changes added to commit (use "git add" and/or "git commit -a")
Reset the changes
Now, let’s try to reset one commit back.
% git reset --keep @~
error: Entry 'file' not uptodate. Cannot merge.
fatal: Could not reset index file to revision '@~'.
As you can see, git reset --keep
prevents us from losing our changes.
If you use git reset --hard
, you will lose your changes.
% git reset --hard @~
HEAD is now at <commit-hash> Create a file