I have a shell script I am working on that monitors something and currently runs in the terminal showing the output if a condition matches. If there is a match I want it to run a block of code every x number of seconds for a certain amount of time - it doesn't really matter if it repeats for a certain amount of time or a certain number of times as that can equate to the same thing.

Note: it won't be repeating from when the script is run, but from when a condition matches and it could be triggered again when there is another match and that second trigger could happen while the previous repeat is going on, in which case I would want to start the repeat again from the latest trigger event.

How would I do this?

  • I don't understand your description; if a second trigger happens while a repeat is running, does it start a second set of repeats (running in parallel with the first), or just extend how long the already-running repeat loop will run? Also, this question would probably be a better fit on stackoverflow, but you should include enough code from your current script for readers to see the structure (i.e. just the specific parts that relate to the test and loop, but enough that someone could try it out). – Gordon Davisson Nov 9 at 17:51
  • Me too, I've been trying to understand what you are trying to do, but it just doesn't make sense to me. – Ljm Dullaart Nov 11 at 21:23
  • Yes, I wasn't very clear. I would want the second trigger to take over from the first rather than having the processes overlap. – Ally Nov 12 at 22:04

So, if I understand you correctly, what you want is something like this:

#!/bin/bash
qty_xeq=15
x=2 # every x number of seconds
trigger_condition=0

triggertest(){
    # test if the condition is true
    if [ $condition ] ; then
          trigger_condition=1
    fi
}
i=0
while true ; do
    triggertest
    if [ $trigger_condition = 1 ] ; then
        while [ $i -lt $qty_xeq ] ; do
            i=$((i+1))
            trigger_condition=0
            do_the_action
            sleep $x
            triggertest
            if [ $trigger_condition = 1 ] ; then
               i=0
            fi
            trigger_condition=0
        done
    else
        sleep $x
    fi
done

Not the nicest code, but you should get the ideae.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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