Wiki source for SyntaxFunction


Show raw source

======Functions======

Functions can be declared in two forms, with or without the keyword "function". These forms behave identically.
In both forms the arguments to the functions are passed as positional parameters ($1 .. $N)

Note: prior to version 1.0.5 "function name ()" and "name ()" behaved differently. The former syntax caused all variable references to be local.
From version 1.0.5 onwards this has been fixed to conform to the behaviour of bash/ksh where variables are all global unless the "local" modifier is used.


=====Declaring Functions=====

===name () { list; }===
===function name () { list; }===
===function name { list; }===

This declares a function "name". The different variations in syntax are equivalent. The body of the function when executed runs in the same context as the parent shell, with the exception of Positional Parameters ($1 ... $N).
This means that variables assigned within the function have a "side effect" of writing into the global environment for the current shell.
Note: starting with version 1.0.5 local variables can be defined.

Example

%%

setit ()
{
A=$1 ;
}

A="no value"
echo $A
setit value
echo $A
%%

Result
%%
no value
value
%%

=====Local Variables=====

Variables can be marked local using the "local" keyword. Local variable modifications are scoped to the function (and any function or script it calls) and do not affect the global (or parents) variables of the same name.

%%
setit ()
{
local A=$1
echo in setit A is $A
}

A=Value1
setit Value2
echo Outside of setit A is $A
%%

Results
%%
in setit A is Value2
Outside of setit A is Value1
%%


======Return Value======

The Return value of a function is the return value of the last command, or the argument of the [[CommandReturn return]] function. Return values can be any type,
including XML and object types. If the return type is numeric it is available as $? when run using command syntax. Any value is available when executed using [[SyntaxFunctionCall Function Call Syntax]]

Example
%%
foo ()
{
true ;
}

foo && echo Is True
%%

Result
%%
Is True
%%

Example

%%
foo ()
{
return 2 ;
}

foo
echo $?
%%

Result
%%
2
%%

====Function Call Expressions====

See [[SyntaxFunctionCall Function Call Syntax]]


----

[[CoreSyntax]]
[[Commands]]
[[Functions]]




Valid XHTML :: Valid CSS: :: Powered by WikkaWiki