0

This is my simplified script.

I am wondering if the proc() can know if it is run directly or through the runner.

#!/bin/bash
runner () {
    "${@}"
}
proc() {
    eval 'version=$(echo "SUCCESS: **** ${BASH_VERSION} ****")'
    echo -e "$version"; 
    return 0
}

runner proc
proc

What do you think?

conanDrum
  • 457

1 Answers1

3

proc is not a separate process in your example. It's just a function, run in the same process as the main shell.

The $FUNCNAME array gives it access to its backtrace:

foo(){ bar; }
bar(){ baz; }
baz(){ proc; }
proc(){ echo "${FUNCNAME[@]}"; }

$ foo
proc baz bar foo main

So yes, it can:

case ${FUNCNAME[1]} in runner) ...

If you experiment with it, you will see that running it in a subshell / subprocess doesn't break the backtrace or affect it in any way:

foo(){ (bar &) | cat; }
=> same output
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • true, I clarified my title. let me check what I can do with your info. thanks a bunch – conanDrum Jun 14 '19 at 00:02
  • I've added an example test and a note about functions, backtraces & subprocesses –  Jun 14 '19 at 00:14
  • excellent mosvy thanks mate – conanDrum Jun 14 '19 at 00:37
  • I tested with calling a function like this 'bash ' and like this 'runner bash ' and the function is oblivious to who is calling it, based on your suggestion. Any other suggestions in this case? – conanDrum Jun 14 '19 at 06:35
  • The backtrace will not work through exec, ie. processes which start an external command. For that to work, Unix will have to be something like a Lisp Machine ;-) –  Jun 14 '19 at 06:42
  • True. this is something new. I actually do not expect anything. In this case it is just only out of curiosity and I will not open a new thread for this. Just wondering if there is a way. – conanDrum Jun 14 '19 at 06:46
  • if you have time can you please take a look at this? https://unix.stackexchange.com/questions/524811/not-working-when-running-bash-filename-function-through-process-substi?noredirect=1#comment970741_524811 – conanDrum Jun 14 '19 at 06:47
  • I guess you can pack the FUNCNAME array and pass it through an environment variable, and then unpack it in the script run via bash, but I don't think there's anything automatic. –  Jun 14 '19 at 06:48
  • @conanDrum I gave it a try. The essential part is that in external_command > >(...), the process running inside >(...) will be a child of the process running external_command and a granchild of your script. –  Jun 14 '19 at 07:13
  • Thank for taking the time Mosvy, appreciated. Just looking to bypass this with as little pain as possible. Currently I am looking at replacing all commands in this script with functions and running the funcitons instead. Unless you can think of a way I can capture this PID? – conanDrum Jun 14 '19 at 07:17