0

Any ideas how restore my changes I made in step 2 below?

  1. Git checkout new branch foo
  2. Made some changes on foo.txt
  3. Save foo.txt (no commit though)
  4. Git checkout back to branch master
  5. Git checkout file foo.txt
  6. Made some changes on foo.txt
  7. Save foo.txt (no commit)
  8. Git checkout back branch foo
  9. All changes in foo.txt from step #2 are disappeared
jjk
  • 592
  • 1
  • 6
  • 23
  • 6
    You can't. The changes are gone. When you `git checkout` a file, you're saying "overwrite the current file, even if it has changes." – Jonathan Hall Jun 29 '19 at 14:39
  • 3
    You didn't even run `git add` on the file? – Stanislav Bashkyrtsev Jun 29 '19 at 14:52
  • See also [Why git keeps showing my changes when I switch branches (modified,added, deleted files) no matter if I run git add or not?](https://stackoverflow.com/q/5531362) – ChrisGPT was on strike Jun 29 '19 at 15:22
  • 1
    Re: *Save foo.txt (no commit though)* — only *commits* actually save anything in any permanent way. You can use [Stanislav Bashkyrtsev's suggestion](https://stackoverflow.com/a/56818553/1256452) to try to find the temporary object from a `git add`, but without a `git commit` that temporary object may be removed within a couple of weeks. – torek Jun 29 '19 at 16:06

1 Answers1

3

If you ran git add on that file after you changed it, the content has been registered in .git - it's present there and it can be retrieved. Though not easily - you'd have to find all the recent objects that were created by Git first:

find .git/objects/ -type f -printf "%T+\t%p\n" | sort

These are sorted by modification date, so the last ones were created recently. Make your way up - go through each of those objects and run this command until you find your content:

git cat-file -p [40 letter hash including 2-letter directory name]

Some of those objects are not files but trees (directories) and commits, skip them.

If you didn't run git add then Git doesn't know about that file at all, so you can't ask Git to retrieve the file back.

Stanislav Bashkyrtsev
  • 14,470
  • 7
  • 42
  • 45