I used git reset --hard command and lost all my files. Then tried to use command git fsck which got me a dangling tree with a hash value. Then entered the git show --format=raw <hash value> which gave me list of all the lost files.
git fsck --lost-found gave me
Checking object directories: 100% (256/256), done.
notice: HEAD points to an unborn branch (master)
notice: No default references
missing tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
dangling tree d2682fde785bcfd92525e5b856770c084fd32ee8
ls .git/lost-found/other gives me a hash file which when opened by the command git cat-file -p d2682fde785bcfd92525e5b856770c084fd32ee8 gives me all my lost files in this format.
040000 tree 29faf839a8e17b98198fa8e56a6abb8933a3ab78 models
040000 tree ba9e0d882162283f3590f6d3cbcdc038cf71e8a2 node_modules
100644 blob 2ff009cc3552ee4e0ac3b0babc968797f9527b90 package-lock.json
100644 blob 2b27f9894f180d2e65c468ea261c1bf96c372801 package.json
040000 tree 7254925ba8ee0d8a8313368a017be7bbc0c3a178 routes
100644 blob 6726fd46ff7359e2409a5ff9b3e5b3768fc3c31b server.js
Please help me out on how to recover these files back to my folder.
With discussion among the community, I ended up getting the answer to my doubt suggested by @Philippe.
After following the steps mentioned in the doubt I got the list of all lost files but could not recover them in the original format.
Coming to the answer, the answer lies in the doubt itself. Like how I accessed the hash file in .git/lost-found/other by the command
git cat-file -p d2682fde785bcfd92525e5b856770c084fd32ee8similarly we have to replace the hash value in the command with the file we want to recover with a greater than symbol and the name of the file where the content should be saved.ie, for example, I want to recover the file server.js so the command should be
This command copies the content in the hash file in a file called server.js
P.S. Take care of some points.
always keep an eye on which directory you are currently in. It affects which your all commands as it decides at which location the file will be stored.
the above solution is only for a blob (server.js, package.json etc.).
To recover the files from a tree you need to again use the command
git cat-file -p <hash-value of tree>followed by a greater than symbol>and test.txtie, for example I want to recover files which is in models. So the command goes like
this creates a temp.txt text file which has a hash file of the file inside the models folder like this
Now to access the content or code of this file repeat the steps mentioned in the answer.