How do I break out of loops if any one is success and add retires?

166 Views Asked by At

I have a mikrotik script which will try to resolve some domains. I am currently using :foreach.

:local piholeDNS "192.168.xxx.xx"
:local piholeUP [/ip firewall nat print count-only where comment~"pihole_bypass" && disabled]
:local success;

:foreach i in $testDomains do={
    :do {
        :resolve $i server $piholeDNS
        :set success true
        } on-error={
            :set success false
            }
} 

But the issue is that I want the script to break out from the loop as soon as any one of the domains gets resolved and set success true. Also, In case of failure, it should try to resolve each domain 3/4 times (number of retries). So, far the above script does work, with some minor issues.

1

There are 1 best solutions below

0
On

Since Mikrotik doesn't provide any equivalents to last or break to exit the loop, your best bet is probably to simply skip the remainder of the loop if "success == true".

For the retry, you simply need to enclose the original loop in another for loop that counts to 4. Something like the following is probably what you want:

:local piholeDNS "192.168.xxx.xx"
:local piholeUP [ /ip firewall nat print count-only where comment~"pihole_bypass" && disabled]
:local retry
:local success

:set success false
:for retry from=0 to=3 step=1 do={
    :foreach i in $testDomains do={
       :if (success = false) do={
           :resolve $i server $piholeDNS
           :set success true
       } on-error={
           :set success false
       }
    }
}

This will still run through the loop for all of the domains 4 times, but it won't do anything for each iteration if success is already true, so that won't matter much.

If you look here, you might also be able to do something cleaner by putting the loop inside a function (See Functions below the conditionals and loops sections) by returning as soon as it succeeds, YMMV.

https://wiki.mikrotik.com/wiki/Manual:Scripting#Commands

Hope that helps.