Does echo run a sub-shell in a parallel process?

This is my construct (just an example):

echo -e "hello: [$(cat file.txt)]" 

In 90% of cases, it works fine, and the outputs ( foo is in file.txt ):

 hello: [foo] 

But in 10% of cases I see (I donโ€™t know when and why exactly this happens):

 hello: [] foo 

Why is this happening?

ps. Actually my code is as follows:

 STDERR=$(mktemp /tmp/bash-XXXX); { something } 2> >( tail -100 | tee $STDERR ); CODE=$?; if [ $CODE != 0 ]; then echo -e "ERROR ${CODE}: \"$(cat ${STDERR})\""; fi rm -f ${STDERR} 
+4
source share
1 answer

You have a race condition here.

 tail -100 | tee $STDERR 

created, but most likely sleeping on fifo (since it is still empty). You write programs in fifo ("something"), but fifo has buffers, so it writes everything and continues. Then, at some non-specific time, the tail / tee wakes up - sometimes too late: this means that $ STDERR is still empty when the cat reads it.

How to fix it: you cannot easily synchronize with the completion of work with a tee / tail. Use

 { something; } 2>&1 | tail ... | tee 

Do you need another way to telegraph $? from {something}. I will come back to this.

  • One way: install

    set -o pipefail

    so that each fault-tolerant component in the pipeline sets the exit status for the pipeline.

  • Another way is to query the PIPESTATUS array (see bash (1)).

Hope this helps

+1
source

Source: https://habr.com/ru/post/1500995/


All Articles