Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store a function in a unix variable

I am a newbie to unix. I am wondering if there is any way to assign a function to a unix variable, like:

temp=funcname(){echo 'I am in function'};

$temp; // prints I am in function.

Please let me know.

like image 927
Kannan Lg Avatar asked Sep 09 '26 17:09

Kannan Lg


1 Answers

Functions are not first-class in UNIX shells. However, you can store the name of your function in a shell variable and call it thereby.

funcname_foo() {
  echo "I am a function"
}
temp=funcname_foo
"$temp"

That said -- if you wanted to point to a different function conditionally, you could just as easily define it conditionally:

if [ "$foo" = bar ] ; then
  funcname() { echo "Function A"; }
else
  funcname() { echo "Function B"; }
fi
funcname # actually call the function

It is possible to define a function using text from a variable through use of eval; however, this is error-prone and contrary to best practices, and generally should not be done.

If you described your actual use case, a better example of the right way to achieve your desired result should be possible.

like image 165
Charles Duffy Avatar answered Sep 12 '26 16:09

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!