11/11/2005

Using relative directories from shell

I'm a stickler for using exactly the same code in production and development environments. One nice solution to this problem, even though it's not officially 100% possible to do in Unix, is to use directories relative to your executable for all config/support/data files.

I say officially, because in theory a program can be started in such a way that it's mistaken about where it lives. But it's only in really rare cases, done on purpose, that this comes up in practice.

Anyway, in Perl there's nice little module called FindBin that lets you do this easily. But I've never known how to do it nicely in shell.

Well, this bit of ksh seems to work in every case I've tried:

Bin=$(d=$(dirname $0);print $d | grep '^/' || print $(pwd)/$d)

Pretty cool, eh? I'd always thought that if you run something from your $PATH variable, $0 would only have the name relative to whatever it matched in your path. But it turns out modern shells are much nicer about it than that, and always pass the full path from / in this case.

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home