Appending argv entries to an array (dynamically populating an array) in bash
13,501
Solution 1
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 $#
Solution 2
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
Solution 3
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.
Author by
qiushuitian
a programer on iOS plantform~~ enjorying life... I'm a chinese.
Updated on June 07, 2022Comments
-
qiushuitian almost 2 years
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.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. -
chepner over 11 yearsBash has supported simple arrays for a very long time; bash 2.0, released in the mid 90s, supported them. I hope no one is using a version that doesn't.
-
glenn jackman over 11 yearsmake sure you quote
"$arg"
when you append it to the array. -
Charles Duffy over 11 yearsPlease don't suggest the ABS as a documentation source -- it's out-of-date and often has advice that's flat wrong. mywiki.wooledge.org/BashGuide is more actively supported and maintained.
-
Qnan over 11 years@CharlesDuffy might be, I just picked the top link from Google, mostly because pointing to lmgtfy is not too constructive. The point is that there're numerous resources on the subject.