Bourne shell differences w.r.t functions?

Chet Ramey chet at cwns1.CWRU.EDU
Tue Sep 18 01:50:18 AEST 1990


In article <3693 at segue.segue.com> bruce at segue.segue.com (Bruce Adler) writes:

I wrote:
$ >Systems with /bin/sh based on the AT&T s5r3 /bin/sh.  This version of
$ >the shell preserves the dollar variables around a series of function
$ >calls.  The s5r3.2 /bin/sh also allows recursive functions.

$ I don't think this is precisely correct.  Perhaps you meant that only 
$ the *positional* parameters are preserved around a function call.  The
$ *local* variables aren't preserved.

Yes, I meant the positional parameters.  AT&T Bourne shells do not have local
variables.  All variables are global.

$ What does the following script do on your system:
$ 
$ 	#!/bin/sh
$ 	set -- yes
$ 	lvar="yes"
$ 	foobar() { lvar=$1; }
$ 	foobar no
$ 	echo positional variable $1, local varibale $lvar

The /bin/sh running on my system is bash.  Running your script unmodified
says positional yes, local no.  Changing the script so that `lvar' is a
real local variable (making the script read `local lvar=$1'), says
positional yes, local yes.

$ My s5r3.2 based Bourne shell says positional yes, local no.  If your 
$ shell doesn't preserve local variables then it's difficult to implement
$ real recursive functions (i.e. a function that invokes itself).

True, but the s5r3.2 sh does not prohibit them:

zen$ sh53 				<----- s5r3.2 sh
zen$ f()
> {
> if [ $1 -eq 0 ] ; then
>         return
> else
>       echo $1
>       f `expr $1 - 1`
> fi
> }
zen$ f 5
5
4
3
2
1

It just limits their usefulness.

Chet
-- 
Chet Ramey				``Levi Stubbs' tears run down
Network Services Group			  his face...''
Case Western Reserve University	
chet at ins.CWRU.Edu		



More information about the Comp.unix.shell mailing list