Unix/Linux environment variables for simpletons

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.

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

Simple :smack:, Cool :cool:, Thanks :slight_smile:

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

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

I believe that . works in all bourne shells, but don’t quote me on that,

The $SHELL environment variable should be set to the path of the shell.