change array value while looping in bash

10,429

Solution 1

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]=

Solution 2

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
Share:
10,429
VextoR
Author by

VextoR

Updated on July 25, 2022

Comments

  • VextoR
    VextoR almost 2 years

    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?

  • VextoR
    VextoR over 10 years
    This helped! btw, it has another error in if [ -z "${SourceFolder[$i]}"]; then it says [: missing ]'` why is that?
  • UmNyobe
    UmNyobe over 10 years
    again, watch your spaces. should be [ -z "${SourceFolder[$i]}" ]