The stateful generator
This is a parameter expansion with state:
cycle=(0 1)
ref='cycle[i++%2]'
i=0; echo ${!ref} ${!ref} ${!ref} ${!ref} # 0 1 0 1Four expansions of the same word produce four different evaluations. No function call, no subshell, no loop—an iterator implemented entirely in expansion.
Two bash facts conspire. First, array subscripts are arithmetic contexts: whatever sits between the brackets goes through arithmetic evaluation, side effects included, so evaluating cycle[i++%2] increments i. Second, indirection defers evaluation: ref holds the unevaluated string cycle[i++%2], and ${!ref} resolves it fresh at expansion time. Assign the string once, and every subsequent ${!ref} steps the generator.
Written directly, ${cycle[i++%2]} would also increment—the load-bearing part of the indirection is that the subscript survives as data. You can pass ref around, store it in another variable, hand it to a function, and the receiver gets a value that ticks on every use. Widen the array and the modulus for round-robin over anything: hosts, colors, log prefixes.
Arithmetic evaluation inside subscripts is the same machinery behind a documented family of bash injection problems—the evaluator will run command substitutions and nested expansions that arrive inside a subscript string, which is how “array index” becomes “arbitrary code” when the index came from input you don’t control. This trick is for literal expressions under the script author’s control; untrusted input must not become part of the subscript.
Also bash-only: zsh spells indirection ${(P)name} and treats subscripts differently, so the idiom does not port.