如何在bash中获取调用者函数的调用方法

如何在bash中获取调用者函数的调用方法

根据下面的代码,是否可以$caller_method从下面的伪代码函数中获取函数的调用者是否正常调用函数的值eg:mytest 1或使用子shell样式eg: echo "(mytest 1)"

#!/bin/bash
function mytest() {

      # THIS IS PSEUDOCODE
      if $caller_method=directly; then
         echo "THIS WAS CALLED DIRECTLY"
         # Do other stuff
      elif $caller_method=inside_a_subshell; then
         echo "THIS WAS CALLED INSIDE A SUBSHELL"
         # Do other stuff
      fi
     # END OF PSEUDOCODE
}
    
    # CALLER 
    # Calling mytest directly
    mytest 1
    # Calling mytest inside a subshell
    echo "$(mytest 1)"

预期输出:

THIS WAS CALLED DIRECTLY
THIS WAS CALLED INSIDE A SUBSHELL

那么, mytest() 函数是否能够理解或存储信息,无论它是否是使用此方法调用mytest 1$(mytest 1)

另外,我不想从调用者函数传递任何额外的参数,例如$(mytest 1 call_inside_a_subshell)mytest 1 call_directly

答案1

我刚刚发现这个问题与如何使用内置变量检测我们是否位于子 shell 中有关$BASHPID 如何检测我是否处于子 shell 中?

所以代码可以写成:

#!/bin/bash

function mytest()
{
    if [ "$$" -eq "$BASHPID" ]; then
        echo "THIS WAS CALLED DIRECTLY"
    else
        echo "THIS WAS CALLED INSIDE A SUBSHELL"
    fi
}

# Calling mytest directly
mytest 1
# Calling mytest inside a subshell
echo "$(mytest 1)"

答案2

我认为这是可以做到的。尝试这个:

#!/bin/bash

function mytest() {
    # THIS IS PSEUDOCODE
    if [ $ORIGINALBASHPID -eq $BASHPID ]; then
        echo "THIS WAS CALLED DIRECTLY"
        # Do other stuff
    else
        echo "THIS WAS CALLED INSIDE A SUBSHELL"
        # Do other stuff
    fi
    # END OF PSEUDOCODE
}

# CALLER
ORIGINALBASHPID=$BASHPID
# Calling mytest directly
mytest 1
# Calling mytest inside a subshell
echo "$(mytest 1)"

它输出:

THIS WAS CALLED DIRECTLY
THIS WAS CALLED INSIDE A SUBSHELL

相关内容