A rather dull worKLOG. This is just a scratchpad for solutions to IT problems that might be useful to someone else. Expect no opinions, no brilliant insights and definitely no pictures of pets or children. Expect stack traces, code snippets and other hints for the Google Indexer.

Thursday, January 11, 2007

How can a bash or shell script find its own directory?

It's often desirable to write a small bash script to launch an
application. However, you want the application to be portable, so you
don't want to hard-wire absolute file locations into the script.
Unfortunately, this means that if you execute the script from somewhere
other than the directory which holds the script, then it won't locate
the files. A bit of googling suggests that the general problem of
making a script aware of the directory in which it resides is quite
hard. However, the following works for me:
cwd=`dirname $0`
old=$pwd
cd $cwd
#launch your application here, for example
nohup python main.py &
#where main.py is in the same directory as the script
cd $old