在bash中,是有可能得到函数体内的功能的名称? [英] In BASH, is it possible to get the function name in function body?

查看:111
本文介绍了在bash中,是有可能得到函数体内的功能的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在BASH,是有可能得到在函数体的功能的名称?采取以下codeS为例,我想在它的身上打印功能名称为测试,但$ 0似乎是指脚本的名称,而不是函数名。因此,如何让功能的名称?

 #!/斌/庆典功能测试
{
    如果[$#-lt 1]
    然后
        #如何在这里得到的功能的名称?
        回声$ 0件产品1>和2
        1号出口
    科幻
    当地NUM =$ {1}
    回声$ {NUM}
}#正确的函数
测试100#缺少的参数,函数应该退出错误
测试退出0


解决方案

尝试 $ {FUNCNAME [0]} 。此数组包含当前调用堆栈。引述手册页:

  FUNCNAME
          包含所有shell函数名称的数组变量
          当前在执行调用堆栈。索引为0的元素
          是任何当前执行的shell函数的名称。该bot-
          TOM-大多数元素是主。只有当存在这个变量
          外壳函数执行。分配到FUNCNAME没有
          影响并返回一个错误状态。如果FUNCNAME没有设置,它
          失去其特殊性能,即使是随后复位。

In BASH, is it possible to get the function name in function body? Taking following codes as example, I want to print the function name "Test" in its body, but "$0" seems to refer to the script name instead of the function name. So how to get the function name?

#!/bin/bash

function Test
{
    if [ $# -lt 1 ]
    then
        #   how to get the function name here?
        echo "$0 num" 1>&2
        exit 1
    fi
    local num="${1}"
    echo "${num}"
}

#   the correct function
Test 100

#   missing argument, the function should exit with error
Test

exit 0

解决方案

Try ${FUNCNAME[0]}. This array contains the current call stack. To quote the man page:

   FUNCNAME
          An  array  variable  containing the names of all shell functions
          currently in the execution call stack.  The element with index 0
          is the name of any currently-executing shell function.  The bot‐
          tom-most element is "main".  This variable exists  only  when  a
          shell  function  is  executing.  Assignments to FUNCNAME have no
          effect and return an error status.  If  FUNCNAME  is  unset,  it
          loses its special properties, even if it is subsequently reset.

这篇关于在bash中,是有可能得到函数体内的功能的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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