On Thu, 28 Feb 2008, Dan Armbrust wrote:

> Thanks for all the feedback - this turned out to be quite informative.
>
> So, I seem to have the following 2 methods:
>
> P1=$(\dirname "$(\which "$0")")
>
>
> P2=$(cd "$(\dirname "$0")"; pwd)
>
> And they both seem to work in all the cases that I'm worried about, 
> anyway.  And if I followed the thread correctly, method two is better, 
> because it doesn't depend on any behavior from "which" - and that is 
> good, because which is not necessarily consistent across all platforms.

Right.  As the inventor of "P1," I would definitely recommend that you 
stick with "P2".  Also, "P2" works even with a newline in the path name 
(admittedly a very weird phenomenon).

Just remember to run it early in the shell script before any cd commands 
or else it can fail.


> However, since I barely know enough shell scripting to be dangerous, can 
> someone please explain to me why the second method works?  Why doesn't 
> the cd command leave me in a different place than where I started, if I 
> execute the script from another folder?  Does cd get executed twice?

There are two issues here:

(1) Like Vegas, a lot of what happens in the shell script stays in the 
shell script.  If you change your default directory in the script, it 
changes only in the script and not in your login shell -- so when the 
script is done, you will always "be" where you "were."  This is because 
the script runs in its own shell.

(2) Kathryn put the cd command within parentheses so that it would run in 
a subshell which means that it would not affect the default directory for 
the rest of the script.  You changed it slightly by putting a dollar sign 
in front of the parenthesis -- I think that is good and it is doing just 
what you want because the $() enclosure also creates a subshell.

Mike