31.4. How Does Unix Find Your Current Directory?
[ This article is about the standard Unix pwd command, an external (Section 1.9) command that isn't built into your shell. (The external pwd is usually stored at /bin/pwd.) Most shells have an internal version of pwd that "keeps track" of you as you change your current directory; it doesn't have to search the filesystem to find the current directory name. This article describes how the external version finds the pathname of its current directory. This isn't just academic stuff: seeing how pwd finds its current directory should help you understand how the filesystem is put together. -- JP]
A command like pwd inherits the current directory of the process that started it (usually a shell). It could be started from anywhere. How does pwd find out where it is in the filesystem? See Figure 31-2 for a picture of the current directory /usr/joe and its parent directories. The current directory doesn't contain its own name, so that doesn't help pwd. But it has an entry named . (dot), which gives the i-number of the directory (Section 10.2).
Figure 31-2. Finding the current directory name
The current directory has i-number 234. Next, pwd asks Unix to open the parent directory file, the directory one level up, through the relative pathname (..). It's looking for the name that goes with i-number 234. Aha: the current directory is named joe, so the end of the pathname must be joe.
Next step: pwd looks at the . entry in the directory one level up to get its i-number, 14. As always, the name of the one-level-up directory is in its parent (.., i-number 12). To get its name, pwd opens the directory two levels up and looks for i-number 14, usr. Now pwd has the pathname usr/joe.
Same steps: look in the parent, i-number 12. What's its name? Hmmm. The i-number of its parent, 12, is the same as its own -- and there's only one directory on the filesystem like this: the root directory (/). So pwd adds a slash to the start of the pathname and it's done: /usr/joe.
This explanation is really missing one or two parts: filesystems can be mounted on other filesystems, or they can be mounted across the network from other hosts. So at each step, pwd also needs to check the device that the current directory is mounted on. If you're curious, see the stat(2) manual page or check a Unix internals book. Also see the last few paragraphs of Section 10.4 for more about the links between directories.
Copyright © 2003 O'Reilly & Associates. All rights reserved.