0

Any idea how I can declare a bash array with a variable embedded?

For example, i is a integer that increments in a for loop. I want to continue to increment i and append it to the end of the array being declared like so:

declare -a DB$iFIELDS
DB$iFIELDS[$j]=blah blah blah
6
  • So you want to create a new array every time in loop OR append to an existing array? Commented Apr 30, 2014 at 19:20
  • This is just creating a new (incremented) array each time. There is a separate loop that fills the array. Commented Apr 30, 2014 at 19:36
  • Ok show your code to clarify Commented Apr 30, 2014 at 19:36
  • 1
    Use printf: printf -v DB${i}FIELDS[$j] '%s' "blah blah blah". By the way, Bash is not exactly supposed to be used this way... Commented Apr 30, 2014 at 19:48
  • 1
    @gniourf_gniourf is right. If your data structures are getting this complicated (and really, it doesn't take much), it's time to pick another language. Commented Apr 30, 2014 at 19:50

1 Answer 1

1

You can use declare to make the assignment as well, since to some extent the [] is as much a part of a variable name as it is an indexing operator.

$ i=3
$ declare -a DB${i}FIELDS
# ...
$ j=6
$ declare "DB${i}FIELDS[$j]=blah blah blah"
$ set | grep "DB.*FIELDS"
DB3FIELDS=([6]="blah blah blah")
Sign up to request clarification or add additional context in comments.

1 Comment

yes, declare works fine with indexed (-a) and associated (-A) arrays.

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.