2

I have a command that runs forever and periodically output stuff until it gets killed by something else (similar to tail -f), and I want to make it so that whenever there's new output another command gets executed.

Caveats:

  • I can't use Bash
  • That command obviously isn't tail, it just behaves in a similar manner
  • That command's output doesn't always come in lines, and I do not intend to execute that other command for each line of the output
  • Polling is not an acceptable solution

1 Answer 1

4

Here is an example of using dd to trigger a shell command whenever something is read from stdin, whether terminated by newline or not:

{
   printf not-nl-terminated
   sleep 1
   printf '%s\n' nl-terminated
   sleep 1
   echo
   sleep 1
   printf 'binary\0data'
} | 
while : ; do
   input=$(dd bs=1M count=1 2>/dev/null | tr '\n\0' __)
   [ "$input" ] || break
   printf 'input of size %d\n' "${#input}" 
done

will give

input of size 17
input of size 14
input of size 1
input of size 11

This snippet from the standard spec may help understand dd's behavior when bs= is used explicily:

If the bs= expr operand is specified and no conversions other than sync, noerror, or notrunc are requested, the data returned from each input block shall be written as a separate output block; if the read returns less than a full block and the sync conversion is not specified, the resulting output block shall be the same size as the input block. If the bs= expr operand is not specified, or a conversion other than sync, noerror, or notrunc is requested, the input shall be processed and collected into full-sized output blocks until the end of the input is reached.

3
  • yes, thanks for the correction.
    – user313992
    May 5, 2019 at 3:31
  • in any case the command line substitution at input=$(dd bs=1G count=1 2>/dev/null) is going to cause the trailing newline to be eaten.
    – iruvar
    May 5, 2019 at 3:41
  • Yes, that's why it says "13 bytes". If needed, that could be worked around with input=$(...; printf x); input=${input%x}
    – user313992
    May 5, 2019 at 3:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .