View Full Version : Unix/Linux environment variables for simpletons
01-31-2009, 05:54 PM
I am new to the Unix/Linux world and could do with some help regarding environment variables, shell scripts and the like. As I understand it if I have the following in a shell script:
then $MYVAR is available within the remainder of the script and to any commands called within it, but not to the shell that called the script. This thwarted my naive plan to create a script which set up a bunch of environment variables, which could then be called from other scripts as required :(. Is there a simple way to achieve what I was trying to do.
01-31-2009, 06:03 PM
What you want to do is source the script that sets the variables:
Run my_script.sh, and it will print "value".
01-31-2009, 06:17 PM
Simple :smack:, Cool :cool:, Thanks :)
01-31-2009, 06:24 PM
Also, be aware that various shells have different commands. For instance, export isn't universal; in csh, you would use setenv.
In addition, I'm pretty sure that not all shells recognize "." as equivalent to "source".
01-31-2009, 08:42 PM
If you have a script that you'd like to run in a new subshell (so that when it ends, your current environment is unchanged) you do what you did in the OP. If you want to run the lines of the script in your current shell, thereby modifying its environment, you have to "source" the script, like so:
contents of blah.sh:
Then at your prompt:
myprompt> source blah.sh
Bash has an alias for "source", namely the period (.), so you could type ". blah.sh" instead of "source blah.sh". Tcsh doesn't have this. To find out what shell you are running, type "ps" and look for "bash" or "tcsh". (It is possible but unlikely that you are running a shell other than these.)
The tcsh equivalent of the above script would be:
setenv MYVAR "foobar"
setenv MYOTHERVAR 65
01-31-2009, 09:17 PM
Bash has an alias for "source", namely the period (.), so you could type ". blah.sh" instead of "source blah.sh".
I believe that . works in all bourne shells, but don't quote me on that,
To find out what shell you are running, type "ps" and look for "bash" or "tcsh". (It is possible but unlikely that you are running a shell other than these.)
The $SHELL environment variable should be set to the path of the shell.
vBulletin® v3.8.7, Copyright ©2000-2016, vBulletin Solutions, Inc.