Friday, October 3, 2008

export not working in shell script - solution

Another small problem and another nice thing learnt :o)

I was trying to make a shell script that exports all my environment variables as I was tired exporting them manually each time I connected to my lab machine from my computer. I wrote the script and tried running. to my surprise it was printing the echo statements but not exporting the variable. After searching for 5 minutes on the web I found that when we try exporting some variables it runs in a private shell. This make the changes not visible in the current shell.

I found this on a linux forum and found it interesting:
The program that you use to access the shell is called a terminal emulator. Examples are Konsole, Gnome Terminal, xterm, Eterm, aterm, etc. When you open one of these, the program also creates a subshell. The shell that you enter commands into is different from the one running your X server, though it has inherited all the attributes of the main shell.

When you run a script in a shell, that script runs in a subshell that works very similarly. A script runs in its own environment, and does not affect the parent at all. When the "source" command is used, changes to the subshell are duplicated in the parent shell


http://www.linuxforums.org/forum/linux-newbie/55168-export-doesnt-work-shell-script.html
so the solution:
simple ... run your shell script with the following command
test_script.sh=>

#!/bin/sh
export MY_TRACE_FILE=/root/mytrace.trc;

and then do a

. ./test_script.sh

or

source ./test_script.sh


I tried the second one and it worked just fine :)

Wednesday, October 1, 2008

Code for Random Number Generator

This is something I always thought of doing but it was always a priority 2 task for me. Today when I was in a fix of keying in make and make install each time I had to run my test I finally replaced the libuuid patch with a simple 3 line code of this random number generator function.

int temp_id=0;

void myRandomNumber()
{
unsigned int myseed;
myseed = (unsigned)time(NULL);
srand(myseed); // Initialize the random number generator
temp_id = rand(); // Random number
}



Reference:
http://www.randombots.com/random_control.htm


Vaibhav