How does bash continue to work correctly when you move its working directory

cd-commanddirectoryopen filesrename

On Linux, I moved a directory to another directory using mv, and in another shell, my working directory happened to be the directory that was moved.

I ran hg pull in that shell, and to my surprise, it ran correctly in the new working directory – without me having to type cd.

How did that work?

Best Answer

Moving a file or directory changes the meta-data property that identifies its parent in the file tree, but it doesn't change its actual node id. On the physical disk it's still in the same place, and the filesystem still knows it as the same object. Anywhere the file or directory pointer is open, it is already connected to that object, and a change to the objects meta-data won't affect open processes. Things will only break when you try to to open a new pointer based on the file system path.

By the same token you can move a file that is being written to and the writes will keep going to the new location; because it's actually the same file node, just re-attached to a different place in the file structure. Neither the physical location on the disk nor the node id changes, the file system just updates its internal map of nodes on the disk to paths in the filesystem.

Also of note, this behavior only applies when the moved object stays on the same file system. If you move it from one mount to another the physical location of the node has to change and the object will get deleted from the original file system, leaving dead pointers!