1

I am trying to generate a new array, with the combination of other arrays, respecting a specific sequence. In pure Bash. Example:

numbers=(0 1 2 3 4 5 6 7 8);

colors=(red blue green);

loop_sequence=(numbers numbers colors numbers colors colors)

Example of out:

0
1
red
2
blue
green
3
4
red
5
blue
green
6
7
red
8
blue
green
0
1
red
2
blue
green...

But I find very difficult to make the internal loops of iterations. Any help is very welcome.

1

1 Answer 1

0

You can use this script:

numbers=(0 1 2 3 4 5 6 7 8)
colors=(red blue green)
loop_sequence=(numbers numbers colors numbers colors colors)    
numLen=${#numbers[@]}
colLen=${#colors[@]}

arr=() # output array
max=3 # max counter
for ((r=0; r<max; r++)); do
   for i in "${loop_sequence[@]}"; do
      [[ $i == numbers ]] && arr+=("${numbers[$((n++ % numLen))]}") ||
             arr+=("${colors[$((c++)) % colLen]}")
   done
done

printf "%s\n" "${arr[@]}"

Output:

0
1
red
2
blue
green
3
4
red
5
blue
green
6
7
red
8
blue
green
Sign up to request clarification or add additional context in comments.

6 Comments

on debian, bash 4 , i get: declare: -n: invalid option
declare -n is new to bash 4.3
@Fredfs: Check updated answer. It should work in older BASH versions as well.
why your 'max counter' is set to 3 ?
That is just an example value. Set it to any number you want.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.