On Wed, 27 Feb 2008, Dan Armbrust wrote:

> I'm trying to find a variable or a command that will tell me where the 
> currently executing script lives.
>
> So, If I'm running /foo/bar.sh, I'm looking for a something that will
> give me "/foo/", while I'm inside the script bar.sh.
>
> On windows, this is "%~dp0".
>
> On linux, `pwd` isn't right all the time, because it tells the
> location the script was executed from, not where it lives.
>
> $0 is not normalized, it can have all sorts of interesting paths in it.
>
> The best I have come up with so far is:
>
> PROG=`which $0`
> PROGDIR=`dirname $PROG`
> echo $PROGDIR
>
> But I'm not yet convinced that this will always work.

You'll have a problem with spaces.  This would fix that problem by using 
quotation marks:

PROG=`which "$0"`
PROGDIR=`dirname "$PROG"`
echo $PROGDIR

But if that's all you want to do, you can shorten it to this single line:

echo $(dirname "$(which "$0")")

I *think* that will always work in bash, but then I am not an expert on 
bash scripts.

Did you see this?:

http://www.linuxquestions.org/questions/programming-9/discovering-script-directory-path-531088/

That might help.  This guy is totally wrong, so ignore him!:

http://unixjunkie.blogspot.com/2006/08/old-but-useful-shell-tricks.html

Mike