1

Why does example 1 output text flaswlessly but example 2 (I waiting 5 seconds) doesn't?

example1:

$ ping google.com 2>&1 | sed "s/^/[PING_GOOGLE]/"
[PING_GOOGLE]PING google.com (216.58.212.206) 56(84) bytes of data.
[PING_GOOGLE]64 bytes from lhr25s27-in-f14.1e100.net (216.58.212.206): icmp_seq=1 ttl=117 time=23.1 ms
[PING_GOOGLE]64 bytes from ams16s21-in-f206.1e100.net (216.58.212.206): icmp_seq=2 ttl=117 time=14.7 ms
[PING_GOOGLE]64 bytes from ams16s21-in-f206.1e100.net (216.58.212.206): icmp_seq=3 ttl=117 time=12.8 ms
[PING_GOOGLE]64 bytes from ams16s21-in-f206.1e100.net (216.58.212.206): icmp_seq=4 ttl=117 time=12.1 ms

example 2:

$ ping google.com 2>&1 | sed "s/^/[PING_GOOGLE]/" | sed "s/^/[dewi22]/"
$
markp-fuso
  • 28,790
  • 4
  • 16
  • 36
dewijones92
  • 1,319
  • 2
  • 24
  • 45
  • 1
    I suspect `sed` buffers its output in a (rather large) buffer if its standard output is not a terminal. The same behavior occurs if you replace the second pipe with an output redirection. – chepner Mar 17 '23 at 14:34
  • 1
    Try with `sed --unbuffered` if you have GNU `sed`. – M. Nejat Aydin Mar 17 '23 at 14:35
  • Also, if you ensure `ping` terminates before the buffer is full, you'll see all the output at once when `ping` finishes. `ping -c 10 | sed '...' | sed '...'` – chepner Mar 17 '23 at 14:36
  • Another hint: If you want `| sed 'A' | sed 'B'` you can use `| sed 'A; B' instead`. – Wiimm Mar 17 '23 at 14:41
  • 1
    "not printing output the moment it's generated" != "not working"; when ping exits, or enough content builds up, it'll all get flushed. – Charles Duffy Mar 17 '23 at 14:54
  • See [BashFAQ #9](https://mywiki.wooledge.org/BashFAQ/009) – Charles Duffy Mar 17 '23 at 14:55
  • Also, you can try to use a single `sed` command which accomplishes the same task : `ping google.com 2>&1 | sed 's/^/[dewi22][PING_GOOGLE]/'` – M. Nejat Aydin Mar 17 '23 at 15:09

0 Answers0