bash process substitution + using same variable in main and sub-process

143 Views Asked by At

If I do

x=42
IFS= read -r x < <(echo "$x")
echo "$x"

am I guaranteed to get back 42, or is there a race condition like for reading from / writing to the same file in a pipeline (cat /tmp/x | grep -v pat | cat >/tmp/x)?

OK, for read it's kind of obvious, what about mapfile -- might it clear the destination (= source for subprocess) array before forking off the substituted process?

arr=( 'forty' 'two' )
mapfile -t arr < <(printf '%s\n' "${arr[@]}")
declare -p arr

Edit: maybe a better comparison would be to

{ echo 42; echo 13; } >/tmp/x
cat >/tmp/x < <(grep -v 13 /tmp/x)
cat /tmp/x
1

There are 1 best solutions below

3
On

using same variable in main and sub-process

Each process has it's own space. They are separate variables.

am I guaranteed to get back 42

Yes.

might it clear the destination (= source for subprocess) array before forking off the substituted process?

No.

The subprocess <(...) has a copy of all the parent environment. It does not affect parent in any way.