BASH: loop array values unlimited

Viewed 83

In bash I want array let say:

array=(1 2 3)

Then I need a loop for program where

x will be 1,2,3,1,2,3... (from array)

i will be unlimited 1,2,3,4,5,6.... (main loop)

My code:

array=(1 2 3)
while true ; do
 ((i=i+1))
 #screen -dmS plot$i -d /destinatin$x
 echo $i $x
 sleep 1
done

I do not know how to loop array and set $x to go 1,2,3,1,2,3....

2 Answers

Infinite loops are generally generated using the shell built-in command : which does nothing in its singular form. So if you want to loop infinitely over the elements of a list, you can do the following:

1. The infinite nested while-for loop:

while :; do for i in "${a[@]}"; do echo "${i}"; done; done

2. using an index-reset

i=0; while :; do echo "${a[i]}"; ((i=i+1)); ((i==${#a[@]})) && i=0; done

2. using modulo calculation:

i=0; while :; do echo "${a[i]}"; (( i=(i+1) % ${#a[@]} )); done

3. the infinite for loop with modulo index

for ((i=0;;i++)); do echo "${a[i%${#a[@]}]}"; done

This code should solve your problem:

#!/bin/bash

array=(1 2 3)
i=0
count_of_elements=${#array[@]} #counting the number of array elements

while true; do
rest=$(($i%$count_of_elements)) #counting rest of the division by count of array elements
printf "${array[$rest]}," #dispay result
i=$((i+1))
done

It will be also working if you change your input array (for example if it will be array=(1 2 3 4 5).

Related