Operating System - HP-UX
1758417 Members
3037 Online
108869 Solutions
New Discussion

defining a global variable

 
SOLVED
Go to solution
Lawrence Mahan
Frequent Advisor

Re: defining a global variable

In general all shell variable are global within a shell script. However: If you are calling non shell routines within the script then the varables within those routines will be local to that routine. What I meen by a non shell routine is if you are using awk, perl, sql, or other executables that can be called in-line from shell that is not shell. Usually you will have to pass varables to this routines. I.E. awk -v INDATE=${INDATE}
A. Clay Stephenson
Acclaimed Contributor

Re: defining a global variable

Actually, one can have local variables within a shell script. Those defined in functions via the typeset command are local to the function. Run this script and it should make variable scoping clear.

--------------------------------------------
#!/usr/bin/sh

typeset -i I=100 # global
typeset GLOVAR="Global String"

func1()
{
typeset -i I=1 # local definition

echo "I in func1 = ${I}"
echo "GLOVAR in func1 = ${GLOVAR}"
return 0
} # func1

func2()
{
typeset -i I=2 # local definition

echo "I in func2 = ${I}"
echo "GLOVAR in func2 = ${GLOVAR}"
return 0
} # func2

func1
func2
echo "I in main = ${I}"
echo "GLOVAR in main = ${GLOVAR}"
exit 0

----------------------------------------


It's considered good practice to typeset all variables in scripts. Of course, any of these can be exported and made available to child processes.

If it ain't broke, I can fix that.