1

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 (i.e. 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.

2 Answers 2

9

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 ]
Sign up to request clarification or add additional context in comments.

4 Comments

ah got it.. i knew it would be something simple.
I remember reading somewhere this morning that a single '=' acts as an assignment.
Not inside a test expression. bash allows you to use == as a synonym for equality =, but it's not part of the POSIX specification.
@ziggy Tip: shellcheck automatically points out both these issues and a few others
2

One more way

Change your loop to:

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

As Suggested by chepner Change conditional statement to:

if [ "${currentValue}" = A ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.