0

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

So, does the mytest() function able to understand or store an information whether it has been called using this method mytest 1 or $(mytest 1) ?

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
  • 443

2 Answers2

2

I just found out this issue is related how to detect if we are in a subshell using a built-in variable $BASHPID How can I detect if I'm in a subshell?

So the code can be written:

#!/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)"

MaXi32
  • 443
1

I think it can be done. Try this:

#!/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)"

It outputs:

THIS WAS CALLED DIRECTLY
THIS WAS CALLED INSIDE A SUBSHELL
nobody
  • 1,710