I deleted a file using sudo rm -r when on a dev branch locally . Now I can still view the file on other branches but I don't quite understand it fully. Also I think I have lost the file on the master branch.Need help.
In Git, files are not in branches. Files are in commits. Commits are read-only (entirely) and permanent (well, mostly). No existing commit can ever be changed.
The commits are in various branches, but the set of branches that contain any given commit can change at any time. So if commit a123456...
is in branch B now, and you still have a123456...
but it isn't in branch B tomorrow, nothing happened to the file. At worst, if commit a123456...
isn't in branch B and isn't findable in any other branch either, you might have lost the entire commit.
The files inside each commit are stored in a special, read-only, compressed and de-duplicated format. The de-duplication takes care of the fact that each commit has a full copy of every file, as of the form it had when you (or whoever) made the commit. If some files in commit C1 are the same as those in C2, they're literally shared across those commits and every other commit that has the same copy as well. So if you've lost a123456...
but are pretty sure that file F in that commit is the same copy as file F in some other commit, you can just get file F from the other commit.
Because these files are read-only and de-duplicated and in the end, in a format that only Git itself can read, when you use git checkout
to extract some commit, Git will extract all the files that are in that commit into a regular, ordinary, read/write file stored in the everyday way.
As long as your sudo rm
didn't remove the commits or other internal Git objects (all stored inside the .git
directory), and you weren't in the middle of making some changes, you can just re-extract any of the missing files. To do this, use git restore
(in Git 2.23 or later) or git checkout
(in older versions of Git). Note that git checkout
can also check out an entire commit, which is probably not what you want to do; the fact that one single command—git checkout
—can do either of two very different things ("restore one file" or "check out one entire commit") is why it was split up into two new separate commands in Git 2.23. (The old git checkout
remains, though, and will remain for years, for compatibility.)