将函数存储在unix变量中 [英] store a function in a unix variable

查看:47
本文介绍了将函数存储在unix变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Unix的新手.我想知道是否可以将函数分配给unix变量,例如:

  temp = funcname(){echo'我在功能中'};$ temp;//打印我在运行. 

请让我知道.

解决方案

在UNIX shell中,函数不是一流的.但是,您可以将函数的名称存储在shell变量中,然后调用它.

  funcname_foo(){回声我是一个功能"}temp =功能名称_foo"$ temp" 

也就是说-如果您想有条件地指向其他函数,则可以轻松地有条件地定义它:

  if ["$ foo" = bar];然后funcname(){echo"Function A";}别的funcname(){echo"Function B";}科幻funcname#实际调用函数 

可以通过使用 eval 使用变量中的文本来定义函数;但是,这是容易出错且与最佳做法相反的,通常不应这样做./p>

如果您描述了您的实际用例,那么应该有一个更好的例子来说明达到所需结果的正确方法.

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.

解决方案

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.

这篇关于将函数存储在unix变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆