Tuesday, December 21, 2010

FindBin equivalent in bash

Perl has a really useful module called 'FindBin'. Using this module, one can find the actual directory of the current script and also can find the real name of the script (when the current script is just a symlink). What's the equivalent of it in bash? Answer is 'FindBin.sh'.
I wrote this bash script to imitate the behavior of both $FindBin::RealBin and $FindBin::RealScript. You can find this script here. I uses the environment variable 'PATH' to figure out the dir name and actual name of the current script.

How use it?
It's really simple! 'FindBin.sh' currently accepts 2 command line options: '-bin' and '-script'. '-bin' is equivalent to FindBin::RealBin and '-script' is to 'FindBin::RealScript'. After these commandline options, just pass the name of the current script. (which is generally stored in $0).
Example: myRealBin=`FindBin.sh -bin "$0"` 

Help?
Use the '-h' option with this script in order to know about its usage.

Happy coding!

No comments:

Post a Comment