Dan Dinh
Dan Dinh

Reputation: 8619

Wait for the subshell in Bash IO redirection

The scenario is that I need my main command to run in current shell, this is required or losing all environment stuff, etc.

So, I can't just run my pipe this way:

#command-line 1
mainCommand | (
  ...subshell commands...
) &

#this wait works, but main command is in child process
wait $!

I have to run main command in current shell:

#command-line 2
mainCommand &> >(
  ...subshell commands...
) &

#this wait is waiting for mainCommand, not subshell
wait $!

However, in the command line 2, it's just a single command and I can't just send it to background, only the subshell should go to background then I can get its PID.

How to let

I have the lock file solution but I prefer not using file as the whole script runs continuously and writing/modifying a file again and again is like penetrating the file system.

Upvotes: 1

Views: 588

Answers (2)

Jay jargot
Jay jargot

Reputation: 2868

Give a try to this. you need to add a kill in the subshell commands.

sleep 100 &
export BACKGROUNDPID=$!

mainCommand &> >(
  ...subshell commands...
  kill "${BACKGROUNDPID}"
) &

wait ${BACKGROUNDPID}"

# execution continue here ...

Upvotes: 1

chepner
chepner

Reputation: 532053

Newer versions of bash allow waiting on a process substitution, but until then, I would recommend simply using a named pipe.

mkfifo p
( ... subshell commands ... ) < p &
mainCommand > p
wait

Upvotes: 2

Related Questions