0

what is wrong with this line

Array$j[$i]="10"

when I use this line on my bash script, I got this error: command not found. I think the problem refers to $j. because when I change above to

Array[$i]="10"

I do not get any error. But I need this declaration. because on my bash file. I have to define multiple array with this name

Array1, Array2 , Array3 and ... .

How to chage this line to work correctly:

Array$j[$i]="10"

Ps. j is an loop index. and it give number j=1, j=2, ...

1
  • was able to usethe 'let' command as well...let Array$j[$i]=10; tempvar=Array$j[$i];echo ${!tempvar}; stackoverflow.com/a/16524913 Commented Aug 10, 2014 at 14:05

4 Answers 4

2

Your problem is not about arrays but variables in general, as you can not do j=foo; $j=bar to get a variable foo with value bar.

You can use eval or declare, at the beginning of the line, to make the substitution before setting the value.

Example:

for i in 1 2 3; do
  for j in 1 2; do
    eval array$j[$i]=foobar

    varname=array$j[$i]
    echo ${!varname}
  done
done
Sign up to request clarification or add additional context in comments.

3 Comments

whould you please add echo to the for ? I mean please add echo array$j[$i]. thanks
@alex I just did it (but user000001 already gave the way : indirection).
declare is safer (if only to avoid bad habits) than eval in this case.
2

Use associative arrays if supported (Bash 4.0+):

declare -A Array
Array[$j,$i]=10
echo "${Array[$j,$i]}"

Comments

1

You can use an indirect reference:

$ Array1[0]=10
$ echo "${Array1[0]}"
10
$ j=1
$ arr=Array${j}
$ echo "${!arr[0]}"
10

Comments

1

You can use declare -A to declare the array. This means that the value of $j is expanded before the assignment is made:

$ j=2
$ declare -A array$j="10"
$ echo "${array2[0]}"
10

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.