I think some people aren't getting what the problem is here. The script
has been executed from the command line and we want the script to report
the directory in which it is located. There are four ways that the script
could have been executed:
(1) absolute path
example: /usr/local/bin/script.bash
(2) relative path
example: ../../../local/bin/script.bash
example: ./local/bin/script.bash
example: local/bin/script.bash
(3) in search path ($PATH)
example: script.bash
(4) as above but using globbing
example: local/bin/scri*
In 1-3, the variable $0 will be the command as entered. In "4" the
filename is expanded and $0 becomes that filename, so you really only have
to deal with the first three.
You have to remember that filenames or directory names can contain spaces.
This is a really important little "gottcha" because you can do a whole lot
of testing and think everything is fine because you never use spaces in
filenames. Some people like spaces (are they crazy? ;-), and your program
will not seem so great to them!
Luckily, use of "which," with appropriate quoting around shell variables
to deal with the spaces, seems to work for every case.
Mike