The local Builtin

You can use the local builtin only within a function. This builtin causes its arguments to be local to the function it is called from and its children. Without local, variables declared in a function are available to the shell that called the function (functions are run in the shell they are called from). The following function demonstrates the use of local.

$ demo ()
> {
> x=4
> local y=8
> echo "demo: $x $y"
> }
$ demo
demo: 4 8
$ echo $x
$ echo $y


The demo function, which is entered from the keyboard, declares two variables: x and y and displays their values. The variable x is declared with a normal assignment statement while y is declared using local. After running the function, the shell that called the function has access to x but knows nothing of y.

This entry was posted in bash, Sysadmin. Bookmark the permalink.