Since you seem to be looking for an option you can avoid data loss with, let me present you with a different option.
git stash
allows you to check out HEAD
while saving them to the stash
. You can then undo it with git stash pop
.
So, instead of git reset --hard
, you can do git stash
and it will mostly have the same result.
If you don't like the changes, you can undo it with git stash pop
or if you are fine with it, you can delete the changes from the stash (which is a destructive action) using git stash drop
.
If you also want to include untracked files (which git reset --hard
doesn't do by default), you can use git stash --include-untracked
.
If you don't want to reset to HEAD
(i.e. you want to do git reset --hard some_ref
), you can first stash
the local changes, get the current commit hash using git show-ref
and then run the git reset --hard
. If in doubt, you can reset to the commit again (uness you run git gc
or something like that which cleans up dangling references). However, at that point, you might want to create a branch or a tag as a backup as well.
# Stash your local changes
git stash # add --include-untracked if you want to stash untracked files as well
# get the current commit hash AND SAVE IT somewhere
git show-ref # this will output the commit hash of HEAD
# reset to some ref
git reset --hard some-ref
# In case you want to undo it, reset to the commit hash from git show-ref again and load the local changes from the stash again
git reset --hard YOUR_HASH_FROM_SHOW_REF # replace YOUR_HASH_FROM_SHOW_REF with the hash from git show-ref
git stash pop
In any way, I would recommend you to create a copy of the repository including all changes that are important (just copy the entire directory) in case something goes wrong, especially if you are unsure about the commands.
Also note that git stash
allows you to stash your local changes, check out or reset another ref and then apply these changes back on the newly checked out/resetted ref.