Count number of time loop has run

I have a loop that checks if the SSH outputs a certain message, if so then try the command again until it works.

Is there a way to count the number of times a loop has run?
image

When it gets to a certain number, I then plan to route it down an error path for someone to go and check why and kill the entire flow (which is triggered by a webhook).

1 Like

Hey @RedPacketSec,

If you are using the Split in batches node you can use {{$node["SplitInBatches"].context["currentRunIndex"]}} to get the current index.

4 Likes

You can also use the variable $runIndex in an expression on every node.

3 Likes

Interesting, got any examples of this in use?

Not sure I understand. Gets used like any other variable in n8n.

So if you want to for example exit a loop after a certain number of iterations you can set an expression like the following on the IF-Node:
{{ $runIndex === 4 }}

2 Likes

@jan

{{ $runIndex }} doesn’t seem to be working. It always returns 0. Is this only for batch or should work with the List Item node too?

hey @yuyko I’m running into the same issue. were you able to resolve this or find a workaround?

help is appreciated!

$runIndex will only work inside of a 'Loop Over Items` loop.

You can use $itemIndex to get the index of the item being run outside of the loop, which is essentially the same thing for outside of the loop node

Thanks Liam! that clears it up :slight_smile: