Sunday 25 February 2007

Setting environment variables through bash scripts

Let's say you don't want to have certain variables set every time (through .bashrc). Setting them up by running a script doesn't exactly do what you want: it sets up your variables in the environment in the script, and then exits that environment on exiting the script.

Bash features a built-in command "source scriptname.sh" to do the thing: it executes the commands in the script in the current environment. Here's an example (this is what I wanted to do today, setting extra library and header search paths for gcc):

#my scriptfile
LD_LIBRARY_PATH=/my/nonstandard/dir/local/lib

export LD_LIBRARY_PATH
CPLUS_INCLUDE_PATH=/my/nonstandard/dir/local/include
export CPLUS_INCLUDE_PATH
LIBRARY_PATH=/my/nonstandard/dir/local/lib
export LIBRARY_PATH
cd /take/me/to/the/basedir/of/my/code/project

which, as a bonus, brings me straight to the right working directory to get on the job...
I found this solution starting here from a google search. The gcc variables are described in the book "An introduction to GCC" by Brian Gough, which is in fact also available online.

No comments: