tee coprocess vs tee pipe in Korn shell
I had this piece of code which logged the output of a while loop to a file but also showed it on the screen:
while ... do ... done | tee logfile
A code change required to set a variable in the while loop and make it known after the loop had ended so I tried
while ... do x=123 ... done | tee logfile echo x=$xbut x was empty since in a piped sequence the while loop is considered to be a sub shell and thus it cannot set variables in the parent process.
There is a solution though in Korn shell using coprocesses.
# Start a coprocess to log input to logfile via tee # and report it also to the current tty (tee logfile >/dev/tty)|& # Send output of while loop to coprocess while ... do x=123 ... done >&p echo x=$xwill report x correctly.
This works fine for my example where the script is run always in a terminal window.
If the script is run in the background or via cron its (terminal) output needs to be captured, anything else does not make sense, the script writer had an idea why things would be written to the terminal, surely not just for fun.
download file now