Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

integer variable in korn script not visible throughout script

Status
Not open for further replies.

Blizard

Technical User
Aug 2, 2002
14
0
0
US
I am writing a korn shell script that does a little bit of integer arithmetic, and I find that if I assign a value to an integer variable in a function inside the script, it is not visible in the main program section. Setting the variable as a regular string works, as does setting it as an integer in the main program. Can anyone tell me why?

Here is an example of what I am trying...

#!/usr/bin/ksh
# some comments
setDefaults () {
integer limitpct=85 # This is not visible outside function, even if I export it.
rundate=$(date) # visible everywhere
# other variables, etc. set here
}

# other functions

#####
# Main
######

echo "$limitpct + 1" | bc # gives error, variable not defined.

#this only works if limitpct is set inside main section.

 
integer is an alias for typeset -i

if you typeset inside a function, the variable is local to the function.

 
And since you didn't explicitly declare rundate, ksh will create it as a global variable. There's no way that I know of to declare a variable inside a function and make it global -- you're just going to have to declare limitpct outside the function.
 
Perhaps exporting the variable name would work???
 
Thanks to all for your comments.

I have done a little more testing, and have learned the following:

- If I declare an integer variable in the main part of my script, I can assign a value in a function, and the value will be available to all functions, as well as the main program.
- For a variable defined in the main program, scope is global. In other words, if I declare integer variable int1 in main and assign it a value of 10, and then assign a value of 20 to it inside function func (), the value back in main changes to 20.
- Exporting the variable does not change the behavior. I tried 'typeset -ix', 'set -a', and 'export <var>' without success. It has to be declared in main.
 
One last comment regarding exporting a variable. It makes sense that exporting it within a function will not make it available to the main since the main is a parent of the function, and export simply makes the variable available to the function's children. In other words, the variable becomes available down the line, not up.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top