This is indeed a very popular question on SO. And I think you should remove the part about "usual" and/or "nuts".
–
phuneheheJun 6 '11 at 13:48

The link you provided doesn't address my specific issue. Knowing the current path is not a problem ...it's avoiding having .. point back to the wrong place! And avoiding having to resort to regexes to solve such a simple issue.
–
arnaudJun 6 '11 at 16:13

Your post is a little rambling and some of the statements seem to be contradictory, but if my understanding is correct, you have a $0 of the form foo/scripts/bar.sh, and you're trying to extract the foo part. You furthermore guarantee that there will always be at least two levels of directories in that path (if you only have bar.sh, you're toast). Then you can just strip the last two components of the path:

DIR=${0%/*/*}

You could call your script through scripts/bar.sh, though, in which case the simple pattern replacement wouldn't work. Not to mention calling the script via $PATH. You can make it conditional:

case $0 in
*/*/*) DIR=${0%/*/*};;
?*/*) DIR=.;;
/*) echo 1>&2 "Storing $0 in the root directory is not supported, aborting."
exit 125;;
*) # The script was called through the `PATH`
IFS=:; set -f; unset DIR
for d in $PATH; do
if [ -x "$d/$0" ]; then
# If you put relative directories in your PATH, you get what you deserve.
DIR=${d%/*};;
fi
done
if [ -z "$DIR" ]; then
echo 1>&2 "$0: Fatal error: I can't find myself."
exit 125
fi
unset IFS; set +f;;
esac

Okay, so what you want is for the script being accessed through the symlink to be able to use files relative to the symlink, right? And for that to work even if the path used is absolute, relative, relative from inside the same directory, relative from a subdirectory, etc?

This is indeed not simple. Surprisingly unsimple, in fact - many programming languages have an 'abspath' function which would solve this problem in a flash. However, i do not believe there is such a function in the standard shell script toolkit.

well ...this is incomplete and doesn't solve my problem. Why is it upvoted that much? The issue is about avoiding following the wrong backlinks while avoiding the usage of regexp to find the correct path.
–
arnaudJun 6 '11 at 16:09