ZSH Gem #14: Anonymous functions
I hope, you're familiar with parameter scopes, i.e. local and global variables. Global variables are visible in all contexts including subshells, functions and what not. Local variables are only visible in the current scope (e.g. a function).
You can define a local variable inside a function with the keywords local
, declare
or typeset
:
function() {
local localvariable
}
$localvariable
is only visible inside the function. That means that variables with the same name outside the function are not affected when the variable inside the function is modified.
variable="I'm outside the function"
echo $variable
function myfunc() {
local variable="I'm inside the function"
echo $variable
}
myfunc
echo $variable
the output is:
I'm outside the function I'm inside the function I'm outside the function
You can achieve similar results without functions and the local
keyword by opening subshells:
variable="I'm outside the subshell"
echo $variable
(
variable="I'm inside the subshell"
echo $variable
)
echo $variable
as you might expect, the output is as follows:
I'm outside the subshell I'm inside the subshell I'm outside the subshell
But sometimes you don't want to fork a whole subshell (though a new subshell is not always a new process) but you also don't want to have another function in memory (which you always have to call manually by the way). ZSH has a solution for this: anonymous functions, also known as lambda functions. These are functions without names which aren't stored in memory after they have been executed. To create one, use one the normal function syntax but omit the function name:
function {
echo "Hello World"
}
This function is directly executed and after that ZSH forgets about it. This is pretty helpful if you need a local variable scope but want to have as little overhead as possible. You can declare local variables just like in normal functions. The only difference is that you can't call the function a second time.
variable="I'm outside the lambda function"
echo $variable
function {
local variable="I'm inside the lambda function"
echo $variable
}
echo $variable
Read more about anonymous functions: