MLUG: Re: [MLUG] shell script - find shell script parent directory?
Re: [MLUG] shell script - find shell script parent directory?
Email address obfuscation in effect -- please click here to turn it off.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
On Tue, 4 Mar 2008, Jonathan King wrote:

#!/bin/bash
( cd "${0%/*}" ; pwd -P )

That is very cool and it is similar to what we came up with on TCLUG. There are several little tricks worth adding though. What happens if the filename or directory name begins with a minus sign?

I guess you could escape it...

Suppose you want to make a directory name that begins with "-". Will this work?


mkdir \-X

Nope. A few days ago, I thought it would, but it doesn't. This is where the "--" argument comes in:

mkdir -- -X

That works.  The same trick works for "cd", so we're up to this:

#!/bin/bash
( cd -- "${0%/*}" ; pwd -P )

But, if you try that on a directory beginning with "-" it will still fail! The reason is that it tries to treat the dirname as an argument to *bash*. That one surpised me. So you can do this to avoid trouble:

#!/bin/bash --
( cd -- "${0%/*}" ; pwd -P )

Pretty weird. I did not know about that. I guess we should always use "bash --", right? Unless, of course, we want to provide bash arguments on the command line.


How can we be sure that the bash builtin versions of cd and pwd are used?

Can you over-ride that from happening? In any case, a horrible hack would be to parse the output of "which", which should report that these are built-ins. Note: I don't have a appropriate test bed here at work for any of this.

The key here is that there is a bash command called "builtin". We can use it like so:


#!/bin/bash --
( builtin cd -- "${0%/*}" ; builtin pwd -P )

All that's left now is to make a variable called EXEC_DIR to hold the info, then echo that to stdout.

Mike

_______________________________________________
members mailing list
EMAIL:PROTECTED
http://mlug.missouri.edu/mailman/listinfo/members