When user in a current directory e.g. "/home/test" in Ubuntu bash, if user remove this directory and create it again with another bash, then the directory in old bash is invalid. But it's valid in new bash. can somebody explain why it's happen?
The files in the Linux filesystem are not identified by their path, but by their inode. The new directory has the same path, but it is not the same directory. Your shell is confused that it has a reference to a directory that does not exist any more; the fact that there is another directory with the same path doesn't matter to it. If you do cd $(pwd)
in the invalid directory (i.e. re-enter it), it will be found as valid.
Imagine talking to your boss about the promotion. The next day the boss got dumped and replaced by someone else. You go ask your boss about the promotion, and he says "I have no idea what you're talking about". Both your old boss and your new boss are your boss; but not the same person. Same thingy.
Here's a fun experiment to show this inode-vs-filename difference:
( echo foo ; mv test.txt test2.txt ; echo bar ) > test.txt
One would naively expect that we'd have test2.txt
with foo
and test.txt
with bar
(we write foo
to test.txt
, it gets moved, then we write bar
to test.txt
). But this produces a file test2.txt
with foo
and bar
. The reason is that the redirection opens test.txt
for writing, which involves looking up the path and finding the inode that is assigned to the path, storing it in the file descriptor. From then on, only the file descriptor is used to write (and consequently the inode). When we change the directory entry from test.txt
to test2.txt
, it does not affect the inode.
So what happens is, we look up test.txt
, get inode, write foo
to that inode, change the directory entry to reflect the change in the file name, write bar
to the same inode. This is like chatting with your boss; boss getting fired; but you find him at home and continue chatting with him. His title may have changed, but he's still the same person.