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?

4
  • Have you tried without spaces: a=b and not a = b? Commented Dec 18, 2013 at 9:02
  • @cirosantilli same thing( "=TEST: command not found" Commented Dec 18, 2013 at 9:04
  • Didn't the proposed solution to your previous question work for you? Commented Dec 18, 2013 at 9: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 Commented Dec 18, 2013 at 9:08

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

This helped! btw, it has another error in if [ -z "${SourceFolder[$i]}"]; then it says [: missing ]'` why is that?
again, watch your spaces. should be [ -z "${SourceFolder[$i]}" ]
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

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.