Bash Parameters and Variables: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 25: Line 25:


=Local Variable=
=Local Variable=
If a variable is declared inside a function, it automatically becomes a global variable, and it is visible to the entire shell after the function execution, even after the function exits.


The <tt>local</tt> keyword designates a local variable. Local variables can only be declared inside a function.
The <tt>local</tt> keyword designates a local variable. Local variables can only be declared inside a function.

Revision as of 01:04, 27 May 2016

Internal

Global Variable

Global variables are only maintained within the context of the current shell. Once the shell exits, the global variables are discarded.

The global variables declared in a shell are visible inside the functions executed within that shell and inside functions invoked from function invoked from the shell, recursively.

The value of a global variable is not available to sub-shells, unless the variable is exported.

export

export VAR=VALUE

Declaring a global variable to be exported causes the variable and its value to be copied in the environment of a invoked sub-shell. The sub-shell gets a copy of the variable, not a reference. Modifying the variable from the sub-shell does not reflect into the value of the global variable maintained by the invoking shell.

Variables exported by Sub-Shells

If a sub-shell invoked from another shell exports a global variable, once the sub-shell exits, the exported variables are discarded, and the invoking shell does not sees them.

Local Variable

If a variable is declared inside a function, it automatically becomes a global variable, and it is visible to the entire shell after the function execution, even after the function exits.

The local keyword designates a local variable. Local variables can only be declared inside a function.