简体   繁体   English

Bash脚本:在for循环内填充一个数组

[英]Bash scripting: filling up an Array inside a for loop

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. 注意: “ colors”是某种“ ps -ef”命令,它返回值列表。 it has "blue,red,yellow" values for example. 例如,它具有“蓝色,红色,黄色”值。

colors= 'ps -ef | grep colors'

If your colors are coming in one-to-a-line, you're potentially losing information (dropping the distinction between spaces and newlines, expanding glob characters, etc) as soon as you expand the variable that stores them unquoted. 如果您的颜色是一对一行的,那么一旦扩展了存储未加引号的变量,您就可能丢失信息(删除空格和换行符之间的区别,扩展全局字符等)。

Don't do that. 不要那样做 Instead, follow BashFAQ #1 : 相反,请遵循BashFAQ#1

colors=()
while IFS='' read -r color; do
    colors+=( "$color" )
done < <(get-color-list)

That's even more true if you only want, say, a specific column out of each line; 如果您只想在每一行中指定特定的列,那就更是如此。 read will do the column-splitting for you, making it easier to assign. read将为您完成列拆分,使其更易于分配。

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) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM