How to declare functions as variables
Providing functions as parameters is not intended and will soon get tricky or ugly. The only way I know is via the eval function. Nykakins approach isn't passing a function, but a value, as you can see in this comparing example:
#!/bin/bash
#
# Test providing a function as parameter
#
function f {
param=$1
echo "-----------------------"
date +%T_%N
sleep 0.3
echo $param
date +%T_%N
}
function e {
param="$1"
echo "-----------------------"
date +%T_%N
sleep 0.3
eval $param
date +%T_%N
}
f $(date +%T_%N)
e "date +%T_%N"
The first style evaluates the function 'date' before passing it's result to the client function f, as you can see, because the second time is before the third:
-----------------------
14:00:12_983387321
14:00:12_980980238
14:00:13_287779378
-----------------------
14:00:13_290126185
14:00:13_594301594
14:00:13_596408013
The second block shows, that the passed over function is evaluated between the two date-calls in the e-function.
Maybe you hadn't that strict naming convention in mind, when asking for a function as variable, but I would say that this makes the difference between a function as variable and the result of a function as variable.
Related videos on Youtube
Ziyaddin Sadigov
Updated on September 18, 2022Comments
-
Ziyaddin Sadigov over 1 year
I want to declare variable with pwd() function, which will give me the current path. I want to use pwd() function as ${pwd} variable, something like that. How I must write? Thanks!
-
200_success almost 11 yearsNote that $PWD (all caps) is a special variable in Bash that is automatically set to the current directory path, always. (See "Shell Variables" in the bash(1) man page.)
-
-
Ziyaddin Sadigov almost 11 yearsThanks, @Nykakin! I will make it accepted asnwer very soon!