简体   繁体   中英

Unix bash shell script - Iterating an array in a 'for' loop

I have the following test script:

#!/bin/sh

testArray=(A,B,C,D,E)
currentValue=''
tempValue=x

for i in "${testArray[@]}"
    do
        currentValue=$i

        echo "Processing " ${currentValue}

        if [ ${currentValue}==A ]
        then
            tempValue="$i 123"
        else
            tempValue=$i
        fi

        echo "Current loop " ${tempValue} 
        echo `date`

    done

When i test it, the output that i get is

Processing  A,B,C,D,E
Current loop  A,B,C,D,E 123
Mon Dec 2 20:33:26 GMT 2013

It looks like the 'for' loop in Bash works somehow differently to what i am used to as i was expecting the following output (ie whatever is in the 'for' loop to be repeated for each of the array elements)

Processing  A
Current loop  A 123
Mon Dec 2 20:29:44 GMT 2013

Processing  B
Current loop  B
Mon Dec 2 20:29:45 GMT 2013

Processing  C
Current loop  C
Mon Dec 2 20:29:46 GMT 2013

Processing  D
Current loop  D
Mon Dec 2 20:29:47 GMT 2013

Processing  E
Current loop  E
Mon Dec 2 20:29:48 GMT 2013
  • Why is the 123 at the end?
  • Why is the date command executed only once and not for each iteration
  • What do i do to make each iteration work correctly.

Basically what i am trying to achieve is to write a script that iterates through an array list and execute the same command based on different parameters dependent on the value of the current item in the array. I wrote the above script to try and understand how the for loop works but i am not getting the output i was expecting.

This line

testArray=(A,B,C,D,E)

creates an array with a single element, namely the string 'A,B,C,D,E'. Array elements are separated by whitespace, not commas. Use

testArray=(A B C D E)

You'll also need to add whitespace to your if statement (and technically, you should use = inside [...] , not == , as well as quote the parameter expansion):

if [ "${currentValue}" = A ]

One more way

Change your loop to:

for i in `echo ${testArray} | tr "," " "`

As Suggested by chepner Change conditional statement to:

if [ "${currentValue}" = A ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM