1839550 Members
2378 Online
110147 Solutions
New Discussion

global variable ?

 
SOLVED
Go to solution
Vlad_11
Frequent Advisor

global variable ?

Hi,
I have a series of shell in /workdir and in each of them I'm using same variable declaring it in each script.
Is there any way to define it ounce and make accesible for all shells.

THankss
Mario
beer or not beer
3 REPLIES 3
Sridhar Bhaskarla
Honored Contributor
Solution

Re: global variable ?

Hi Mario,

Yes. What you can do it create one shell script that has all the variables and source-it in from your script. For ex.,

script.rc is as follows

#!/usr/bin/ksh
DATE=$(date)
VAR1="variable 1"
VAR2="variable 2"
LOG="/mydir/mylog"

print_line()
{
echo "$DATE: $LINE" >> $LOG

}


Write your scripts and source-in the above. You can even call teh functions as defined above.

script1:

#!/usr/bin/ksh

. /mydir/script.rc

echo my VAR1 is $VAR1
print_line "test line"

You can form other shell scripts in the same way.


-Sri
You may be disappointed if you fail, but you are doomed if you don't try
A. Clay Stephenson
Acclaimed Contributor

Re: global variable ?

Not as the question is stated. One of the most important concepts of UNIX is that no child may alter the environment of its parent process. You could have a parent process set and export some variable and spawn many children and they would all inherit the variable.

The typical answer to your problem is the . (dot) command. It is used to copy a script into a currently running script; it is not a child process.

For example, create a file call myvars.sh:
VAR1="tom"
VAR2="dick"
VAR3="${VAR1}:${VAR2}"


Now each of your scripts could include myvars.sh:

. myvars.sh
echo "Var1 = ${VAR1}"
echo "Var3 = ${VAR3}"

NOTE: Do not put any exit or return statements in myvars.sh or the foreground process will terminate.
If it ain't broke, I can fix that.
Chris Watkins_1
Respected Contributor

Re: global variable ?

Sourcing a resource file is a common way, as mentioned already.
Another, if it's a variable you need for most of your scripts,
is simply to set and export the variable in your .profile.

(Particularly if these scripts will always be run as the same user)




Not without 2 backups and an Ignite image!