Git – How to Revert to Last Change After git add

git

I am working on a git repo and issue a command

$ git add .

to save the current modifications,

after 10 minutes, I accidentally made some bad changes, so I want to revert to last add . status.

I searched but find there are only methods to reset to latest commit.

How could I return to the status of ten minutes ago.

Best Answer

Short answer is : you can't, git only offers ways to return to previous commits (e.g : stuff you commiittted using git commit)

For future use : you can run git add . && git commit -m WIP to "save current modifications"


Longer answer is : if getting back the previous version of this file is more important than keeping your mental health, you may dig in the list of dangling blobs


Heh, I knew I had some kind of script somewhere :

the following script will list the unreachable blobs, which have not yet been packed in an object pack (this is generally the case with recent blobs), and sorts them by creation date (actually : uses the creation date of the file on disk as an estimation of when the blob was created)

#!/bin/sh

git fsck --no-reflogs --unreachable |\
    grep blob |\
    cut -d' ' -f3 |\
    sed -e 's|^\(..\)\(.*\)|.git/objects/\1/\2|' |\
    xargs ls -l -t 2> /dev/null

Some explanations :

# git fsck --unreachable  ,  if you also use "--no-reflogs" this will search
# through commits which could be reached by the reflog but not by live branches
git fsck --no-reflogs --unreachable |\

# only keep lines mentioning "blob" (files)
    grep blob |\

# keep the 3rd field of the output (hash of blob)
    cut -d' ' -f3 |\

# turn hashes into filenames, e.g :
#   aee01f414061ea9b0bdbbc1f66cec0c357f648fe ->
#   .git/objects/ae/e01f414061ea9b0bdbbc1f66cec0c357f648fe
# (this will be the path of this single blob)
    sed -e 's|^\(..\)\(.*\)|.git/objects/\1/\2|' |\

# give this to ls -lt (list by modification time),
# discard messages saying "file does not exist"
    xargs ls -l -t 2> /dev/null
Related Question