minux minux - 4 months ago 18
Bash Question

Cycle loop in bash script

I made this quick and dirty bash script for this desired result:

1a
2b
3c
4a
5b
6c
......

I made a lot of testing but didn't find a proper way to write it if I can have your suggestions.

Here is the working code I found :

for ((i=1; i<11; i++))
do
echo $((i++))a
echo $((i++))b
echo $((i++))c
done

Answer

Use modular arithmetic to cycle through the list of letters.

letters=(a b c)
for ((i=1; i<11; i++)); do
    echo "$i${letters[(i-1)%3]}"
done

The expression (i-1)%3 will cycle over 0, 1, 2 as i increases.