[comp.unix.wizards] sh functions with "local variables"

dce@Solbourne.COM (David Elliott) (06/07/89)

Here's an interesting problem for all of you sh/ksh wizards out
there.

I normally write shell scripts using a template like this:

	main()
	{
		...
	}
	sub1()
	{
		...
	}
	...
	main ${1+"$@"}	# don't ask, just use it

Now, in modern versions of sh (post SVR2, I think), function parameters
are local to the function, but there's no way to have local variables
otherwise.

Let me clarify this a little.  Yes, if you force a subshell, either
by parenthese or redirection, the changes in the subshell don't affect
the main thread, but that's not really what I'm looking for.

Now, if the function doesn't have any arguments, or if you can use
the arguments early and get rid of them, you can use "set" to put
values in $1-$9, which is one way to have local variables.  Still,
real local variables would be great.

Of course, arrays would be nice, too.

Maybe it's time to implement sh++?

-- 
David Elliott		dce@Solbourne.COM
			...!{boulder,nbires,sun}!stan!dce

kamat@uceng.UC.EDU (Govind N. Kamat) (06/18/89)

In article <1397@marvin.Solbourne.COM> dce@Solbourne.com (David Elliott) writes:
+>Now, in modern versions of sh (post SVR2, I think), function parameters
+>are local to the function, but there's no way to have local variables
+>otherwise.
+>
+>Now, if the function doesn't have any arguments, or if you can use
+>the arguments early and get rid of them, you can use "set" to put
+>values in $1-$9, which is one way to have local variables.  Still,
+>real local variables would be great.
+>
+>Of course, arrays would be nice, too.
+>
+>Maybe it's time to implement sh++?

Well, ksh, which is already around allows you to define true local
variables, using the "typeset" command.  It also includes support for
arrays.

-- 
Govind N. Kamat 			College of Engineering
kamat@uceng.UC.EDU			University of Cincinnati
					Cincinnati, OH 45221, USA

ka@cbnewsh.ATT.COM (Kenneth Almquist) (06/22/89)

>+>Now, in modern versions of sh (post SVR2, I think), function parameters
>+>are local to the function, but there's no way to have local variables
>+>otherwise.

Function arguments were made local in SVR3.

>+>Now, if the function doesn't have any arguments, or if you can use
>+>the arguments early and get rid of them, you can use "set" to put
>+>values in $1-$9, which is one way to have local variables.  Still,
>+>real local variables would be great.

I expect that POSIX (P1003.2) will include local variables, created
using the "local" builtin command.  Ash (which I recently posted to
comp.sources.unix) supports local variables.  Ksh also supports them,
using the "typeset" builtin.
					Kenneth Almquist