是否可以在函数主体中获得函数名称? [英] Is it possible to get the function name in function body?

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

问题描述

在BASH中,是否可以在函数主体中获得函数名称?以下面的代码为例,我想在其主体中打印函数名称"Test",但"$ 0"似乎是指脚本名称而不是函数名称.那么如何获得函数名称呢?

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

推荐答案

尝试 $ {FUNCNAME [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.

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

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