How to make variables in script function local?

Is it possible to make function variables local?
I mean for example, I have a script variable 'name' and in function I have declared variable 'name'
I need to have script's 'name' have the same value as it was before calling the function with the same declaration.

The way to preserve a script var in begining of the function and restore before exiting is last one. I am looking for something more intelligent.

Why?
I have situation, when I need to consolidate many script files into one. Many function in result file use the same variables and call each other.
It was not a problem before as those functions ran in different process, now -the same.

Example:

cat > tst.sh
#! /bin/bash
func1()
{
  var1="asd-func1()"
}

func2()
{
#! /bin/bash
  var1="lkj-func2()"
}

var1=main_body
echo $var1

func1;
echo "after func1: $var1"

func2;
echo "after func2: $var1"
^C
> tst.sh
main_body
after func1: asd-func1()
after func2: lkj-func2()
>

Thanks

func1()
{
  typeset var1="asd-func1()"
}

If there are no variable in the function which need to be changed in the calling script call it in a subshell:

(func1)

Or define the function with parentheses instead of braces:

func1()
(
   : ... whatever
)

If you are using bash or [d]ash you can declare variables to be local to the function (and its subshells, if any):

func1()
{
 local var1 var2=$var2
}

Note that this and the typeset command are non-standard (but local really should be made standard).

Sorry, but i beg to differ: "local" is per default an alias to "typeset" and "typeset" is a shell-builtin keyword.

In fact it is good style to define every variable with typeset prior to using it. Even if it is not necessary it makes the code more reliable (by eliminating possible sources of side effects) and better readable too.

bakunin

Cool!!
Thank you, guys, it's exacly what I was wondering.
And it is good to know how to run script function in subshell. I've thought about that but could not find how.

It may be in some shells. It is not in bash or [d]ash.

It is very bad practice to do so as it is not portable.

$ typeset var
typeset: not found

There is no guarantee that its behaviour will be the same in all shells that do have it.