在bash中将argv条目附加到数组(动态填充数组)

时间:2021-10-12 21:17:53

I'm trying to append content from the argument list ("$@"), excluding $1 and also any value starting with a dash, to an array in bash.

我试图将参数列表(“$ @”)中的内容(不包括$ 1以及以破折号开头的任何值)附加到bash中的数组中。

My current code follows, but doesn't operate correctly:

我当前的代码如下,但无法正常运行:

BuildTypeList=("armv7" "armv6")
BuildTypeLen=${#BuildTypeList[*]}

while [ "$2" != "-*" -a "$#" -gt 0 ]; do
    BuildTypeList["$BuildTypeLen"] = "$2"
    BuildTypeLen=${#BuildTypeList[*]}
    shift
done

My intent is to add content to BuildTypeList at runtime, rather than defining its content statically as part of the source.

我的目的是在运行时向BuildTypeList添加内容,而不是静态地将其内容定义为源的一部分。

3 个解决方案

#1


3  

It's simpler to just iterate over all the arguments, and selectively append them to your list.

迭代所有参数更简单,并有选择地将它们附加到列表中。

BuildTypeList=("armv7" "armv6")
first_arg=$1
shift;

for arg in "$@"; do
    [[ $arg != -* ]] && BuildTypeList+=( "$arg" )
done

# If you really need to make sure all the elements
# are shifted out of $@
shift $#

#2


13  

Append to an array with the += operator:

使用+ =运算符追加到数组:

ary=( 1 2 3 )
for i in {10..15}; do
    ary+=($i)
done
echo "${ary[@]}" # => 1 2 3 10 11 12 13 14 15

#3


2  

There is a plenty of manuals on this subject. See http://www.gnu.org/software/bash/manual/html_node/Arrays.html, for example. Or http://mywiki.wooledge.org/BashGuide/Arrays, or http://www.linuxjournal.com/content/bash-arrays.

关于这个主题有很多手册。例如,请参阅http://www.gnu.org/software/bash/manual/html_node/Arrays.html。或http://mywiki.wooledge.org/BashGuide/Arrays,或http://www.linuxjournal.com/content/bash-arrays。

#1


3  

It's simpler to just iterate over all the arguments, and selectively append them to your list.

迭代所有参数更简单,并有选择地将它们附加到列表中。

BuildTypeList=("armv7" "armv6")
first_arg=$1
shift;

for arg in "$@"; do
    [[ $arg != -* ]] && BuildTypeList+=( "$arg" )
done

# If you really need to make sure all the elements
# are shifted out of $@
shift $#

#2


13  

Append to an array with the += operator:

使用+ =运算符追加到数组:

ary=( 1 2 3 )
for i in {10..15}; do
    ary+=($i)
done
echo "${ary[@]}" # => 1 2 3 10 11 12 13 14 15

#3


2  

There is a plenty of manuals on this subject. See http://www.gnu.org/software/bash/manual/html_node/Arrays.html, for example. Or http://mywiki.wooledge.org/BashGuide/Arrays, or http://www.linuxjournal.com/content/bash-arrays.

关于这个主题有很多手册。例如,请参阅http://www.gnu.org/software/bash/manual/html_node/Arrays.html。或http://mywiki.wooledge.org/BashGuide/Arrays,或http://www.linuxjournal.com/content/bash-arrays。