2 Replies Latest reply: May 20, 2011 10:45 AM by Catch-22 RSS

    BASH: iterate  through an array  passed in

    621560
      I have the following function that does not iterate through the array I want to be able to do some maanipulation on each element in the array[@] Any ideas whats wrong with the below for loop ????

      function foo() {
      name =$1
      array=( "$2" )
      for i in `seq 0 $(( ${#array[@]} - 1 ))`; do
      echo "$i: ${array}"
      echo "./prog $name ${array[i]}"

      done
      }
      NAME ="BLAH"
      arrayP+=("TEST") ;

      arrayP+=("TESTB")
      arrayP+=("TESTC")
      foo $NAME "${arrayP[@]}"

      Edited by: user618557 on 19-May-2011 12:57
        • 1. Re: BASH: iterate  through an array  passed in
          Tommyreynolds-Oracle
          Shell arrays are quite clumsy, but this works:
          #!/bin/bash
          function foo()     {
               name="${1}"
               shift
               array=("${@}")
               for i in $(seq 0 $(( ${#array[@]} - 1 )) ); do
                    echo "${i}: ${array[${i}]}"
               done
          }
          name="BLAH"
          arrayP+=("TEST")
          arrayP+=("TESTB")
          arrayP+=("TESTC")
          foo "${name}" "${array[@]}"
          yields:
          $ ./junk.sh
          0: TEST
          1: TESTB
          2: TESTC
          Yup, very ugly.
          • 2. Re: BASH: iterate  through an array  passed in
            Catch-22
            Your code needs a small correction in order to work, at least when I tried:
            foo "${name}" "${array[@]}"
            should read
            foo "${name}" "${arrayP[@]}"
            However, I would use a different approach, which is perhaps also not as ugly:
            #!/bin/bash
            foo() {
               name="$1"
               for i in $2; do
               set -- $i
               echo "$name $*"
            done
            }
            name="BLAH"
            arrayP+=("TEST")
            arrayP+=("TESTB")
            arrayP+=("TESTC")
            foo "$name" "${arrayP[*]}"
            gives:
            $ ./allarray
            BLAH TEST
            BLAH TESTB
            BLAH TESTC
            I used this also in the previous thread BASH 3.2.25 multidemsional arrays which however, apparently wasn't helpful.