Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 425
qiushuitian Avatar asked Aug 27 '12 08:08

qiushuitian


3 Answers

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
like image 156
glenn jackman Avatar answered Sep 21 '22 18:09

glenn jackman


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 $#
like image 28
chepner Avatar answered Sep 19 '22 18:09

chepner


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.

like image 21
Qnan Avatar answered Sep 17 '22 18:09

Qnan