-
Know your shell and GNU coreutils
Posted on July 25th, 2009 No commentsA friend of mine was frustrated by the fact that in his bash, the `pwd` command gave him the following `unwanted` results:
When he is in the directory `/usr/a`, pwd gives ‘/usr/a/’. In this directory, if he has a symbolic link ‘b’ pointing to /sys/b, then after using `cd b`, pwd gives him `/usr/a/b/` instead of `/sys/b`.
What he wants is the physical/absolute path name as the result, but he can’t get that in bash. (Later we know that we have to use `pwd -P`, but this trick is not stated in `man pwd`, this is in `man bash`) He tried to consult man page, but
man pwdredirects him to the man page of pwd in the coreutils, while using it in shell doesn’t give him the expected result indicated by the pwd command in coreutils . Strange, isn’t it?The problem here is that for commands like ‘pwd’ (and ‘cd’, ‘echo’, etc.), your shell will not actually start a process to execute these commands, instead, your shell has build in functions to do the job. If you consult the man page of pwd, there is one line in the man page stating:
NOTE: your shell may have its own version of pwd, which usually supersedes the version described here. Please refer to your shell’s documentation for details about the options it supports.
Aha! Blame the shell !!!
Why your shell wants to replace the pwd from GNU? Well, the advantage this kind of replacement is that now you have efficiency, because your shell can execute the build in code without forking a new process. The downside is that, now you put your bet on the shell. If the shell behaves differently than you’ve thought, you are screwed.
This is exactly what we want a platform independent tool set. For every Linux distribution, GNU coreutils is always included. If you force your shell to use the pwd from coreutils by typing /bin/pwd, you are insured that even on different platforms with different shells, all results will be the same.
Some shell-dependent features:
alias, echo, cd, printf, background/foreground process (& syntax), pipe and IO redirecting, env variable setting/accessing.Suffice it to say that you should know your shell’s behavior under some circumstances, especially when you want a consistent sh shell scripts behavior.
Happy hacking!
–EOF–
Leave a reply




Recent Comments