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.
Hope this helps
source share