Reputation: 129
I'm having a problem with sed and i can't figure it out, and i'm also amateur.
The objective of my code is to keep monitoring a file(OutputFile.dat) until possible strings(NaN or STOP) are found and then kill the program running on the background. It worked when I'd tried only one string. However when I'd tried to implement more possible matches the code didn't work out.
../program inputfile &> OutputFile.dat &
tail -f OutputFile.dat | sed -n '/NaN/q;/STOP/q'
killall program
I've tried a lot of different things but i can't figure this out. Alternative suggestions to achieve the same thing are also welcome.
Thanks in advance
Upvotes: 3
Views: 101
Reputation: 123470
This is tricky due to buffering and race conditions. The current problems with your code are:
OutputFile.dat is created asynchronously in the background and may not be there when tail
tries to look for it.
You can fix this by opening the file synchronously
program
may buffer output into larger chunks for efficiency reasons, because it doesn't think you care about timing.
You can try to fix this by either asking program
not to buffer, or by using stdbuf
on GNU/Linux.
After sed
recognizes a match, tail will need to detect and write another buffer-full of data before it realizes that, exits, and lets the script continue.
You can work around this by structuring your script to wait for sed
but not for tail
.
Since you say your script works for one keyword, the showstopper for you is likely #3, if your second keyword appears towards the end or a pause in the output.
All together, this would be:
#!/bin/bash
( stdbuf -o 0 -e 0 ../program inputfile & ) &> OutputFile.dat
sed -n '/NaN/q;/STOP/q' <(tail -f OutputFile.dat)
killall program
Upvotes: 4