1

Related questions:

This question ended up not requiring a resolution.

This question had a resolution not involving timeout, but suggested that timeout should work for this purpose when available.

My question:

This command produces no output into foo.txt:

$ cat foo.sh 
#!/bin/sh
sh -c "echo foo; sleep 5; echo bar" | awk '/foo/ {print $1}'
$ timeout 2 ./foo.sh > foo.txt

If I don't redirect into foo.txt, I see foo print out immediately as expected.

On the other hand, the following produces "foo" int the file foo.txt as expected:

$ timeout 2 sh -c "echo foo; sleep 5; echo bar" > foo.txt
$ cat foo.txt
foo

Does anyone know why this may be happening and how best to resolve it? This is a toy example, but the actual script I'm running that led to this problem produces around 100 lines of output on the command line, but also leaves foo.txt empty if it times out before terminating.

Community
  • 1
  • 1
jonderry
  • 23,013
  • 32
  • 104
  • 171

2 Answers2

0

In my experience, this is because pipe "|" wait "echo foo; sleep 5; echo bar" run complete .So after 5s awk can get the output, but timeout terminate the command in 2s so it cannot get the text.

Edit:

Maybe this helps, you can move char (") to the end like this:

$ cat foo.sh 
#!/bin/sh
sh -c "echo foo; sleep 5; echo bar | awk '/foo/ {print $1;}'"
$ timeout 2 ./foo.sh > foo.txt
$ cat foo.txt 
foo
tianyu
  • 179
  • 2
  • 6
0

I found a solution to this. The key is to add fflush() inside the awk script, which seemed to be buffering the output:

#!/bin/sh
sh -c "echo foo; sleep 5; echo bar" | awk '/foo/ {print $1; fflush()}'
$ timeout 2 ./foo.sh > foo.txt
jonderry
  • 23,013
  • 32
  • 104
  • 171