Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash scripting: filling up an Array inside a for loop

Tags:

linux

bash

I try to create an array that is filled up with some values. But i don't know how to do it. I tried something below but it didn't work.

My code:

i=0
for c in colors; do
array[$i]=$c
echo {$c[$i]}
i=`expr $i + 1`
done

note: "colors" is some kind of "ps -ef" command that returns a list of values. it has "blue,red,yellow" values for example.

colors= 'ps -ef | grep colors'
like image 455
AloneInTheDark Avatar asked Dec 26 '22 13:12

AloneInTheDark


1 Answers

You can use this script to fill up the array in a loop:

array=()
for c in $colors; do
    array+=( "$c" )
done

OR even simpler:

array=( $(command) )
like image 196
anubhava Avatar answered Jan 10 '23 02:01

anubhava