A
A
angelok_adclan_20172018-07-20 07:10:51
bash
angelok_adclan_2017, 2018-07-20 07:10:51

How to organize dynamic use of for?

It is necessary to go through all the elements of the array with a step of 2, but the number of elements is not known in advance.
more or less like this:

#!/bin/bash
arr=([1]=1 [2]=2 3 [5]=4 5);
for i in {0..${#arr[*]}..2};do
 printf "[$i]:${arr[$i]}\n";
done

But when processing throws out:
arr.sh: line 4: {0..5..2}: syntax error: expected operand (wrong label "{0..5..2}")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-07-20
@jcmvbkbc

#!/bin/bash
arr=([1]=1 [2]=2 3 [5]=4 5);
eval 'for i in {0..'${#arr[*]}'..2};do
 printf "[$i]:${arr[$i]}\n";
done'

This brace expansion only works with literals. The above solution generates a loop body with literals and puts it in eval.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question