Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are bash function variables parallel-safe when backgrounded?

#!/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?

like image 281
spraff Avatar asked Feb 11 '26 11:02

spraff


1 Answers

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 .

like image 125
KamilCuk Avatar answered Feb 14 '26 21:02

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!