[Code Example] Toggle between two values using bash script

Total
0
Shares

Get bash script code to toggle between two values. This code is best suited for situations where you want to toggle the state of a switch from on/off. It can work for booleans too like true to false and vice versa.

Code Example –

#!/bin/bash

arr=(true false)

cycle() {
    printf '%s ' "${arr[${i:=0}]}"
    ((i=i>=${#arr[@]}-1?0:++i))
}

cycle
cycle
cycle
cycle

# Output:
# true false true false

Inspired from Dylan Araps

Live Demo

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like