Tuesday, February 1, 2011

export environment variable from a bash script


You may want to create a bash script that export some environment variable for your shell, but infect every execution of bash script is a unique session, where the variable export within it can’t be carry backward back to the bash shell.
For example you have a env.sh which contains some environment variables
export HELLO=hello
export HELLO2=world
And you trying to execute the env.sh, then try to echo $HELLO $HELLO2 at your shell, you will get nothing.
The proper way to export environment variable from your script to your shell is using command source.
source env.sh
echo $HELLO $HELLO2
$ hello world
You can put your env.sh into /usr/bin, and you can do source env.sh at any location and it will still works. Just that you have to educate your users to use source instead of direct execute the script. But I realized that not much users aware of the source command.
There is always an alternative way to do the same thing in Linux world. You can create a new bash session from your bash script and make it stay there until user type ‘exit’. Bash support an interactive option for that.
bash -i
Ok, how to make use of it?
Let me gives you a case and explain why I wanna make use of bash -i instead of source.
As an embedded Linux programmer, sometimes I may need to compile some apps by using different set of toolchain based on the embedded device ’s processor architecture. The common environment variable for toolchain are ARCH and CROSS_COMPILE. Besides that, I also want to remind the user regarding that particular shell is meant for building apps for embedded device, therefore I would like to change the color and format of existing bash prompt, which i can make use of PS1 variable.
build_arm.sh
#!/bin/bash
export ARCH=arm
export CROSS_COMPILE=arm-none-linux-gnueabi-
export PS1="\e[31mBUILD_ARM \w \e[m\n\$"

bash -i
When execute build_arm.sh, the bash prompt will turn red, and environment variable for ARCH and CROSS_COMPILE will be set, until user type ‘exit’, everything will resume back to normal. Why? because bash -i interactively wait for user inputs.
./build_arm.sh
BUILD_ARM ~
$

No comments: