1827990 Members
2416 Online
109973 Solutions
New Discussion

global variables

 
SOLVED
Go to solution
Gemini_2
Regular Advisor

global variables

I use ksh and have the following function

function fun1 () {
source=$1
target=$2
}

function fun2 () {
echo $source
echo $target
}

it will not echo $source and $target, because they were defined in a function. how can other function use it? I dont wish to define it in the main....too messy if I have more variables.

2 REPLIES 2
James R. Ferguson
Acclaimed Contributor
Solution

Re: global variables

Hi Gemini:

Actually, the way you have written this, 'source' and 'target' are global once you have called 'fun1'.

If you call 'fun2' first and then 'fun1' the 'source' and 'target' are undefined.

If both functions need to see the variable it must be either global (in main) or you must pass it to function. Within a function you can localize a variable by declaring it with a 'typeset'.

function fun1 {
typeset source=$1
typeset target=$2

Regards!

...JRF...
Gemini_2
Regular Advisor

Re: global variables

yes, I think that I have my function reversed......thank you!!