With Linux the Export Command Works Fine from the Terminal but Not in Scripts, How Can Scripts Provide the Correct Bash Environment Variables?

Problem scenario
EXPORT works when you use it interactively from the command prompt (e.g., bash prompt).  But when you use EXPORT commands in shell scripts, they do not have the desired effect.  You have a Linux script that sets environment variables.  You do not want to log off your terminal or desktop session after the script runs to get the environment variables.  How do you change environment variables via a shell or bash script in Linux without logging off and logging back in?

Rather than run your script a normal way (bash nameOfscript.sh or ./nameOfscript.sh), use the source command.

source nameOfscript.sh

Variables in a user's environment are different from other users.  Shell scripts can be initiated by a given user but the EXPORT commands may not take effect in the shell of that user.  To have the environment variables available with every session, modify the .bash_profile file for the user who needs the variables in his/her environment.  For example, add EXPORT stanzas in the /root/.bash_profile file.  This will give the root user the environment variables on the next time he/she logs in.  But remember that he/she must exit as root user at least once for the environment variables to be updated -- or the script must be ran with the source utility (keyword command).  It is advisable to back up the .bash_profile file before modifying it so you can rollback in case you do something wrong.

Leave a comment

Your email address will not be published. Required fields are marked *