When foo
is run in the background, the BASHPID
of foo
(bashpid_of_foo
) is not available inside the bodies bar_1
to bar_n
via $BASHPID
, since they get invoked via the Command Substitution feature of bash
:
function foo() {
local bashpid_of_foo=$BASHPID
local output
# desired to be shared by all Command Substitutions
# in the body of this function.
local log=/path/to/log.$BASHPID
... >> $log
output=$(bar_1 ...)
...
output=$(bar_n ...)
}
function bar_1() {
# log only specific (and NOT all) messages
# to the shared log file of the invoking thread.
... >> /path/to/log.$BASHPID
}
foo &
foo &
Question: Is there an elegant way around the above limitation, without having to pass bashpid_of_foo
via adhoc environment variables or external disk files?
By elegant, I mean, being able to keep the interfaces and bodies of bar_*
functions clean by relying only on bash-provided features. (Eg BASHPID
is a bash
feature.)
If I try to override the value of BASHPID
, like this,
out_1=$(BASHPID=$BASHPID bar_1 ...)
... it (rightly) complains about BASHPID
being a readonly variable.
EDIT: (1) Added the definition of bar_1
above. (2) Added the 2nd call to foo
in the background. Each foo
invocation needs to maintain its own log file, since writing to a common file could result in garbled contents.
NOTE: Whatever logging happens in the runtime context of foo
, I want it to go into the foo
-specific log file, /path/to/log.$BASHPID
WITHOUT passing around the name of this log file or even the PID of foo
. foo
can have multiple instances running in the background.
BASHPID
may be special, butbashpid_of_foo
is not. You should be able to use that in the command substitutions.$BASHPID
inbashpid
, then the only thing you have to do differently in your command substitutions is to not press shift when typingbashpid
.bash
, but no Perl, Python, Ruby, etc. I fought with him to let me do it inbash
since I'm mostly using/bin
and/usr/bin
commands - coding which in Perl, Python, and Ruby can be relatively more verbose thanbash
. And now I run into this dead-end - which I can surely workaround (like you suggested) but would've preferred not to (by relying some existing facility. Btw, I feel, this is a feature-flaw inbash
: Abash
function (and, not an external program) should be allowed +