Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a range of array elements in bash

Tags:

arrays

bash

i have an array of zeros

declare -a MY_ARRAY=( $(for i in {1..100}; do echo 0; done) )

how to set, for example, 12-25th to "1"? i've tried:

MY_ARRAY[12..25]=1
MY_ARRAY[12:25]=1
MY_ARRAY[12-25]=1  

all not working..

the range 12-25 will be variables obtain from another file. I am looking for a simple solution better not involve in looping

please help

like image 468
once Avatar asked Dec 21 '25 19:12

once


2 Answers

You can use eval here, in this manner:

eval MY_ARRAY[{12..25}]=1\;

If you want to know what is being evaled, replace eval by echo.
Using eval is generally considered as a no-no. But this use of eval here should be completely safe.

On another note,

for i in {1..100}; do echo 0; done

can also be re-written as

printf '%.1s\n' 0{1..100}

EDIT: For start & end being stored in variables, this could work:

$ declare -i start=12
$ declare -i end=12
$ eval $(eval echo "MY_ARRAY[{$start..$end}]=1;")

But in that case, you should really use loops. This answer is only for demonstration/information.

like image 109
anishsane Avatar answered Dec 24 '25 11:12

anishsane


Simple one-liner:-

for i in {12..25}; do MY_ARRAY[$i]=1; done

Refer page Arrays for more manipulation examples.

If the start & end values are stored in variables, the brace expansion would not work. In that case, you should use for loop like this:

$ declare -i start=12
$ declare -i end=25
$ for ((i=$start;i<=$end;i++)); do MY_ARRAY[$i]=1; done
like image 37
Inian Avatar answered Dec 24 '25 11:12

Inian