store a function in a unix variable

2019-07-03 20:15发布

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.

3条回答
戒情不戒烟
2楼-- · 2019-07-03 20:44

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.

查看更多
Bombasti
3楼-- · 2019-07-03 20:47

No. Functions are not first-class in traditional *nix shells.

查看更多
祖国的老花朵
4楼-- · 2019-07-03 20:51

Use function e.g. in the bash shell:

function manhtm { man -R=ASCII $1 | rman -f HTML > ~/tmp/$1-man.html && firefox ~/tmp/$1-man.html;}

function rff { sudo rfcomm connect $1;}
查看更多
登录 后发表回答