简体   繁体   中英

Process substitution >(cmd) doesn't output correctly

I am trying to learn about process substitution and when I execute this:

$ tee >(wc -l) <<< $'aaa\nbbb'
aaa
bbb
$ 2

bash prints the number after the next prompt and waits for me to press enter.

I am using bash 4.4.12 , experiencing the same issue with bash 4.3.48 . There is no issue in bash 4.3.30 and the command correctly outputs:

$ tee >(wc -l) <<< $'aaa\nbbb'
aaa
bbb
2

What could be the possible issue?

It's a quirk / design flaw with process substitution; bash only waits for the main command to terminate. It doesn't wait for substituted processes to end. It creates a race condition when tee ends: does wc finish before bash prints its next prompt? Sometimes it does, sometimes it doesn't.

See this Unix.SE answer by Stéphane Chazelas for a detailed explanation and possible workaround.

When you use process substitution, the process you're substituting runs in the background, and the shell doesn't wait for it to finish before displaying the prompt.

Sometimes it will display its output before the shell displays the next prompt, sometimes it will be a little slower. It has nothing to do with the version of bash, it's just purely by chance which process is faster.

The shell is waiting for you to press enter because it's already displayed the prompt and it's waiting for you to type another command. The shell doesn't know anything about the 2 that was displayed while you were at the command prompt -- that's output, not part of your input.

This is generally not an issue because you don't usually use process substitution with programs that display output to the user interactively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM