bash 递增地添加到数组

bash incrementally adding to an array

考虑下面的代码

#! /bin/bash

declare -a input # unnecessary
declare -a bad
declare -a good # unnecessary

input=('alpha 23' 'bravo 79' 'charlie 12')
echo "input is " ${#input[@]} "long"
for x in "${input[@]}"
do
    bad=$x
    good[ ${#good[@]} ]=$x
    echo 
    echo "added '$x', good is now " ${#good[@]} "long, bad is still " ${#bad[@]} "long"
done

输出是

input is  3 long

added 'alpha 23', good is now  1 long, bad is still  1 long

added 'bravo 79', good is now  2 long, bad is still  1 long

added 'charlie 12', good is now  3 long, bad is still  1 long

根据 bash 的手册页... "When assigning to indexed arrays, if the optional brackets and subscript are supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero."

我显然不理解粗体部分,因为我希望语句 "bad=$x" 每次执行时自动递增索引。它不会并且每次都分配给 bad[0]。

为什么它没有按照我的预期进行,是否有比我分配给 good[ .. ] 的笨拙行更好的代码编写方式

您引用的部分与赋值有关,而不是加法:

array=([0]=zero [1]=one [2]=two)

相当于

array=([0]=zero one two)

这实际上与

相同
array=(zero one two)

要添加到数组,请使用 +=:

array+=(three)

choroba 已经回答了我的问题,正确的代码是

#! /bin/bash

input=('alpha 23' 'bravo 79' 'charlie 12')
echo "input is " ${#input[@]} "long"
for x in "${input[@]}"
do
    output+=("$x")
done

echo "output = (" ${output[@]} ") and is " ${#output[@]} " long "

如果参数中有空格和其他难处理的字符,这对于扫描和处理脚本的参数列表很有用