.
is actually the current working directory in either case; it has nothing to do with the directory holding the script:
[/tmp] $ echo "realpath ." > test.sh && chmod +x test.sh
[/tmp] $ /tmp/test.sh
/tmp
[/tmp] $ cd /usr/bin
[/usr/bin] $ /tmp/test.sh
/usr/bin
An interesting question, indeed. At first glance I see the following advantages:
First of all you state that interpreting ".
" as the current directory may be done by the Shell or by system calls. But having the dot-entry in the directory actually removes this necessity and forces consistency at even a lower level.
But I don't think that this was the basic idea behind this design decision.
When a file is being created or removed from a directory, the directory's modification time stamp has to be updated, too. This timestamp is stored in its inode. The inode number is stored in the corresponding directory entry.
IF the dot entry would not be there, the routines would have to search for the inode number at the entry for this directory in the parent directory, which would cause a directory search again.
BUT luckily there is the dot entry in the current directory. The routine that adds or removes a file in the current directory just has to jump back to the first entry (where the dot-entry usually resides) and immediately has found the inode number for the current directory.
There is a third nice thing about the dot entry:
When fsck
checks a rotten filesystem and has to deal with non-connected blocks that are also not on the free list, it's easy for it to verify if a data block (when interpreted as a directory list) has a dot entry that's pointing to an inode which in turn points back to this data block. If so, this data block may be considered as a lost directory which has to be reconnected.
Best Answer
Most filesystem do not support hard links on directories. However, you can symlink directories.
You can bind mount a directory in Linux, which functions similar to a hard link from a user's perspective. Here is an example:
This is commonly used for chroot environments, since a symlink is relative the chroot's
/
, a bind mount can provide access to locations outside of the chroot.