#!/bin/bash
function foo {
bar=$(cmd_1 $1)
baz=$(cmd_2 $1)
combine_results $bar $baz
}
for arg in $(get_arg_list);
do
foo &
done
Can the multiple instances of bar and baz clobber each other when foo & is run many times? Or are these variables local to each instance?
Are bash function variables parallel-safe when backgrounded?
Yes.
Can the multiple instances of bar and baz clobber each other when foo & is run many times?
No. (Assuming that cmd_1 and cmd_2 and combine_results are themselves "parallel-safe" to execute, as in they will not output a "clobbered" result). All the foo processes write to the same output - the output may be interleaved (but not "clobbered", as in "invalid" or some indeterminate output).
Or are these variables local to each instance?
Yes. (Local, as in, local to the process. The variables are global, ie. ( foo ; echo $bar ) & will print the value of bar set inside the function).
Each subshell is a separate process with its own process space and separate execution environment.
Your variable expansions are not quoted. The for i in $(...) is a common antipattern. Note that you are not pasing any arguments to your function - $1 is unset and expands to nothing. Check your scripts with shellcheck.net .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With