2

The code

SourceFolder[0]=""
SourceFolder[1]="inbound2"
SourceFolder[2]="inbound3"

for i in "${!SourceFolder[@]}"
do    
    if [ -z "${SourceFolder[$i]}"]; then
        ${SourceFolder[$i]} = "TEST"
    fi
done

${SourceFolder[$i]} = "TEST" - doesn't work

it says

=: command not found

How to change value in current loop index in an array?

Rahim Khoja
  • 695
  • 13
  • 26
VextoR
  • 5,087
  • 22
  • 74
  • 109
  • Have you tried without spaces: `a=b` and not `a = b`? – Ciro Santilli OurBigBook.com Dec 18 '13 at 09:02
  • @cirosantilli same thing( "=TEST: command not found" – VextoR Dec 18 '13 at 09:04
  • Didn't the proposed solution to your [previous question](http://stackoverflow.com/questions/20653134/is-it-possible-to-set-a-default-value-for-sparse-array-in-bash) work for you? – devnull Dec 18 '13 at 09:05
  • @devnull yes, the solution in that question is working. But in that case if array size will change I have to edit code with that additional looping, which I don't like( that's why I've decided to go in this way – VextoR Dec 18 '13 at 09:08

2 Answers2

3

Because of the first space = is not interpreted as an assignment. There is a full explanation on So.

Btw ${SourceFolder[$i]} evaluate the array element, which is not what you want to do. For instance for the first one it is the empty string.

Replaces with SourceFolder[$i]=

Community
  • 1
  • 1
UmNyobe
  • 22,539
  • 9
  • 61
  • 90
1

You must change indexnumber in the your array:

ARRAYNAME[indexnumber]=value

ok, you have array is:

array=(one two three)

you can add count to your script for initialize and change element for array indexnumber, example:

#!/bin/bash

count=0
array=(one two three)

for i in ${array[@]}
do
  echo "$i" 
  array[$count]="$i-indexnumber-is-$count"
  count=$((count + 1))
  echo $count
done

echo ${array[*]}

Result:

bash test-arr.sh 
one
1
two
2
three
3
one-indexnumber-is-0 two-indexnumber-is-1 three-indexnumber-is-2
m0zgen
  • 569
  • 7
  • 20