Get bash sub shell output immediately from named pipe

502 Views Asked by At

I have a few commands i run between brackets which i then redirect to a named pipe and tail the pipe however it looks like the redirection happens only after the block has finished executing as i don't see any output from the tail command for a while and it only shows the last command ouput when i do. Any ideas how view the output of the block in realtime?

Example Script

#!/usr/bin/env bash

mkfifo /tmp/why_you_no_out; 
trap "rm /tmp/why_you_no_out" 0;

{ 
    for ((i=1;i<=100;i++)); do 
        printf "$i"; 
    done 
    sleep 10s; 
    printf "\n12356"; 
} >> /tmp/why_you_no_out & 

printf "here"; 

tail -n 1 -f /tmp/why_you_no_out
1

There are 1 best solutions below

0
On

Sounds like the issue is buffering. Most shells don't want to write data a byte at a time because it's wasteful. Instead, they wait until they have a sizable chunk of data before committing it unless the output is connected to your terminal.

If you're looking to unbuffer the output of an arbitrary command, you may find the "unbuffer" utility helpful or any of the solutions mentioned in this question: How to make output of any shell command unbuffered?

If you're dealing with specific applications, they may have options to reduce buffering. For example, GNU's grep includes the --line-buffered option.