local variables in bash

Levi Pearson levi at cold.org
Thu Feb 12 20:42:35 MST 2009


Merrill Oveson <moveson at gmail.com> writes:

> Look at the following bash code:
>
> #!/bin/bash
> func ()
> {
>   echo "\"loc_var\" in func = $loc_var"
> }
>
> func2 ()
> {
>   echo "loc_var inside another function is" $loc_var
>   local loc_var=23
>   func
> }
>
> loc_var=43
> func2
>
> echo "\"loc_var\" outside function = $loc_var"
> exit 0
>
>
> If you run this, you'll notice that loc_var prints as 23.  It should print
> as 43.
> This is a problem with bash - that is if one function calls another the
> value of the local variables are seen.
>
> Does the C shell handle this correctly?

Welcome to dynamic scoping!  This is the way all languages used to work,
at least until Lisp 1.5 and Algol 60.  Even after they figured out
static scoping was good for compiled languages, common wisdom said you
should use dynamic scoping for interpreted languages for years.  

Anyway, dynamic scoping still has its place, but geez.  This is just one
of the zillions of ways that shell script sucks.  Here's a quarter; get
yourself a real language! ;)

                --Levi



More information about the PLUG mailing list