Following Symlinks to Actual Script

I need to have my script know what directory it's in, even if it's run from a symlink located elsewhere. Here's what I've come up with, for the benefit of anyone with a similar need, but I'm also interested to know if there's a more elegant solution. I'd rather not get into awk-land, but I couldn't get the quoting and escaping right with sed.

#!/bin/ksh
prog="$0"
echo "prog='$prog'"
while [ -L "$prog" ]; do
  prog=$(stat --format %N "$prog" | awk '{s=gensub("^.*-> ","","g");print substr(s,2,length(s)-2);}')
  echo "prog='$prog'"
done
dir=`dirname "$prog"`
echo "dir='$dir'"

This perhaps?

#!/bin/ksh
dir=$(pwd -P)

or do you mean the directory the scripts itself is located in?

#!/bin/ksh
dir=$(cd ${0%/*};pwd -P)

There should be no reason to need to know that. Rethink your program design.

You don't need awk:

prog=$(stat --format %N "$prog")
prog=${prog#* -> ?}
prog=${prog%?}