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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12138390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:07:52  来源:igfitidea点击:

Appending argv entries to an array (dynamically populating an array) in bash

arraysbashshelldynamic

提问by qiushuitian

I'm trying to append content from the argument list ("$@"), excluding $1and 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 [ "" != "-*" -a "$#" -gt 0 ]; do
    BuildTypeList["$BuildTypeLen"] = ""
    BuildTypeLen=${#BuildTypeList[*]}
    shift
done

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

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

采纳答案by chepner

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

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

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

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

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

回答by glenn Hymanman

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