In a bash script, I would like to capture the standard output of a long command line by line, so that they can be analysed and reported while initial command is still running. This is the complicated way I can imagine of doing it:
# Start long command in a separated process and redirect stdout to temp file
longcommand > /tmp/tmp$$.out &
#loop until process completes
ps cax | grep longcommand > /dev/null
while [ $? -eq 0 ]
do
#capture the last lines in temp file and determine if there is new content to analyse
tail /tmp/tmp$$.out
# ...
sleep 1 s # sleep in order not to clog cpu
ps cax | grep longcommand > /dev/null
done
I would like to know if there is a simpler way of doing so.
EDIT:
In order to clarify my question, I will add this. The longcommand
displays its status line by line once per second. I would like to catch the output before the longcommand
completes.
This way, I can potentially kill the longcommand
if it does not provide the results I expect.
I have tried:
longcommand |
while IFS= read -r line
do
whatever "$line"
done
But whatever
(e.g. echo
) only executes after longcommand
completes.