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.