Shell Script setting environmental variable hassle

July 8th, 2005


Today, I spent almost the whole day trying to find how to set environmental variable via a shell script I wrote. I found that there is no way to set an environmental variable via shell script. Let me explain to you what I did(note $ stands for shell prompt)

The normal way you would set an environmental variable is to do

$export HELLO_WORLD=hohohohohohoho

then echo will give you

$echo $HELLO_WORLD
hohohohohohoho

From what given above it’s very tempting that writing the script include the export command and executing it would work the same way. To be more lucid, here is what I did, I wrote a script called test.sh which contains

export TEST_VAR=yahooooooooooo

Then, I execute it.

$sh test.sh

The, I tried to see if TEST_VAR contains what I thought. So, I echoed it

$echo $TEST_VAR

What I found was that it doesn’t work echo doesn’t print anything out. TEST_VAR is not in environmental variable list that was quite amazing isn’t it.

I googled about this issue and found what caused this hassle. The important piece of knowledge that would explain this issue is that when we execute a shell script, either via sh or ./ we are executing it with a new, fresh shell. It’s not the same shell as the one we were typing the command sh test.sh. So, the environmental variable TEST_VAR we set, we set it in the shell that we wasn’t meant to set to. So, in the shell where we typed sh test.sh, TEST_VAR wasn’t set to anything. As far as I know, there is no way to fix this.

Entry Filed under: Uncategorized, OSX Tip

Leave a Comment

You must be logged in to post a comment.

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

July 2005
M T W T F S S
    Aug »
 123
45678910
11121314151617
18192021222324
25262728293031

Most Recent Posts