tags:

views:

45

answers:

3

Hi,

I would like to know the code implementation of built-in pwd and /bin/pwd especially when the directory path is a symbolic link.

Example:

hita@hita-laptop:/home$ ls -l
lrwxrwxrwx  1 root root   31 2010-06-13 15:35 my_shell -> /home/hita/shell_new/hita_shell

hita@hita-laptop:/home$ cd my_shell

hita@hita-laptop:/home/my_shell$ pwd <SHELL BUILT-IN PWD>  
/home/my_shell

hita@hita-laptop:/home/my_shell$ /bin/pwd  
/home/hita/shell_new/hita_shell

The output is different in both the cases. Any clue?

thanks

+1  A: 

The shell's builtin pwd has the advantage of being able to remember how you accessed the symlinked directory, so it shows you that information. The standalone utility just knows what your actual working directory is, not how you changed to that directory, so it reports the real path.

Personally, I dislike shells that do what you're describing because it shows a reality different than that which standalone tools will see. For example, how a builtin tool parses a relative path will differ from how a standalone tool parses a relative path.

jamessan
I've never seen a `/bin/cd`, nor do I have any idea how it could work. Can you explain how it would work?
Gabe
You're right. I was thinking of other processes changing directory or accessing relative paths.
jamessan
A: 

The shell keeps track in its own memory what your currenct directory is by concatenating it with whatever you cd to (and eliminating . and .. entries). It does this so that symbolic links don't mess up cd ... The /bin/pwd implementation walks the directory tree upwards trying to find inodes with the right names.

Gabe
Funny description: in my view (archaic), the behaviour of 'cd ..' not going to the parent directory but jumping backwards through a symlink is horrendously counter-intuitive to those brought up on civilized shells that didn't behave the way bash does. If I want to go back, I can use 'cd -' to go to the previous directory. Having to do 'cd -P ..' or 'cd ./..' or whatever is nonsense. But it is largely a question of perspective -- until it screws up a script because it doesn't behave the 'sane' (old-fashioned) way.
Jonathan Leffler
+1  A: 

The built-in pwd shows symbolic links by default, but won't do if you give it the -P option.

In contrast, the pwd command doesn't show symbolic links by default, but will do if given the -L option.

Richard Fearn