1

I have an array setup:

target_array=(
    "item1 -a100 -b250 -caaa"
    "item2 -a110 -cbbb -d1sa"
    "item3 -d2sa -exxx -fyyy"
)

I then iterate over the array and perform various actions:

for target_item in "${target_array[@]}"; do
    #Do Stuff Here
    #and create new items
    x=111
    y=222
    z=333
done

Inside the loop I get new variables and need to add them to the array, so I would end up with something like:

target_array=(
    "item1 -a100 -b250 -caaa -x111 -y222 -z333"
    "item2 -a110 -cbbb -d1sa -x112 -y223 -z334"
    "item3 -d2sa -exxx -fyyy -x113 -y224 -z335"
)

But how can I add these items to the array? Should I be adding them to the existing array, or creating a new array?

I'm trying to port a script from powershell where I would use an 'object' that contained items (item1) and properties (-a) with values (100). But couldn't see a Linux equivalent so an array seemed to be the next best thing.

3

Assuming you are using bash you can iterate over the array using indices, instead of values, with construct ${!array[@]}, and then just replace each element with new value:

for target_item in "${!target_array[@]}"; do
    x=111
    y=222
    z=333
    target_array["$target_item"]+=" -x$x -y$y -z$z"
done

Unfortunately it's not possible in bash to unfold index of an array element from its value.


In zsh you can simplify the procedure with a special so called subscript flag (i) and loop over an array normally:

for target_item in "${target_array[@]}"; do
     x=111                    
     y=222                    
     z=333
     i="${target_array[(i)$target_item]}"
     target_array[$i]+=" -x$x -y$y -z$z"
done
  • cheers, what does the ! in front of target_array do? – IGGt Jan 6 '16 at 13:39
  • @IGGt it means to iterate over array indices, not values. – jimmij Jan 6 '16 at 14:01
0

Creating a new array in the loop and then setting the original array to this new array:

target_array=(
    "item1 -a100 -b250 -caaa"
    "item2 -a110 -cbbb -d1sa"
    "item3 -d2sa -exxx -fyyy"
)

for target_item in "${target_array[@]}"; do
    # Do Stuff Here
    # and create new items
    x=111
    y=222
    z=333

    new_array+=( "$target_item -x$x -y$y -z$z" )
done

target_array=( "${new_array[@]}" )

Using /bin/sh (because I prefer the syntax required to work with $@ over bash's somewhat bulky array syntax):

set -- \
    "item1 -a100 -b250 -caaa" \
    "item2 -a110 -cbbb -d1sa" \
    "item3 -d2sa -exxx -fyyy"

for target_item do
    # Do Stuff Here
    # and create new items
    x=111
    y=222
    z=333

    set -- "$@" "$target_item -x$x -y$y -z$z"
    shift
done

The modified array is "$@".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.