Skip to main content
1 of 2
MaXi32
  • 453
  • 4
  • 14

How to get caller function call method in bash

Based on the following code below, is it possible to obtain the value of $caller_method from the pseudocode function below whether a function's caller has made a function call normally eg: mytest 1 or using subshell style 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)"

expected output:

THIS WAS CALLED DIRECTLY
THIS WAS CALLED INSIDE A SUBSHELL

Also, I don't want to have any extra arguments passed from the caller function such as $(mytest 1 call_inside_a_subshell) or mytest 1 call_directly

MaXi32
  • 453
  • 4
  • 14