PDA

View Full Version : Unix/Linux environment variables for simpletons


ticker
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:

MYVAR=somevalue
export MYVAR

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.

Rysto
01-31-2009, 06:03 PM
What you want to do is source the script that sets the variables:

/etc/variables.conf:
MY_VAR=value

my_script.sh:
#!/bin/sh

. /etc/variables.conf

echo $MY_VAR


Run my_script.sh, and it will print "value".

ticker
01-31-2009, 06:17 PM
Simple :smack:, Cool :cool:, Thanks :)

Digital Stimulus
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".

Pasta
01-31-2009, 08:42 PM
To elaborate...

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:

export MYVAR="foobar"
export MYOTHERVAR=65
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

Rysto
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.