0

I want to throttle output from grep to run at most every X seconds. Specifically I want to do something like this:

ping 8.8.8.8 | grep "No route to host" | throttle 3s | xargs -I % sh -c 'reset wifi'
  • 1
    No, you want to reset WiFi if... See XY problem. – Kamil Maciorowski Aug 22 '18 at 7:28
  • 1
    @KamilMaciorowski -- No, I want to know how to throttle a command. I know exactly what the actual problem and solution are and laying out the problem in 75 steps just to be lead back to this exact question is pointless and a waste of everyone's time. Don't assume that everyone is ignorant about their own questions without even asking a question yourself. It's just rude. – zyklus Aug 23 '18 at 1:51
2

Answering my own question, based on this question, but slightly changed for OSX:

epoch () { date -v+$* "+%s" }

interval () {
    INTERVAL="$*"
    WHEN_TO_RUN=0
    while read LINE; do
        if (( $(epoch 0S) >= $WHEN_TO_RUN )) then
            echo $LINE
            WHEN_TO_RUN="$(epoch $INTERVAL)"
        fi
    done
}

which allows ... | interval 3S

  • Looks reasonable to me. But there seems to be a syntax problem - no semicolon after the arithmetic evaluation (the pair of right parens). Also, LAST_RUN_AT is unused, and of course the basic timing here is pretty coarse, the granularity being whole seconds. But if quality of the pass-through serves the need of the task at hand, see if you can accept your own answer. :-) – sjnarv Aug 27 '18 at 6:04
  • @sjnarv -- If you know how to get epoch time in ms I'll update it to make it more generic – zyklus Aug 27 '18 at 14:39
  • No, I don't have a solution that would be easy for macOS. To be fair, I haven't looked much, so don't take this as definitive info. I have noted that something pretty easy for Linux - pulling a "since the epoch" value that includes nanoseconds via something like date +%s.%N - just isn't supported on macOS (as far as I know, anyway). If I needed a little more accuracy on the intervals on macOS, I might write some C that used gettimeofday(2). – sjnarv Aug 27 '18 at 17:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.