1

So, I'd like to do something like the following:

while [ $n -le 7 ] 
do 
   char$1=somevalue 
   echo $char$1 
   n++ 
done

But even reading through the links below and trying declare or something like $char${!n}, I haven't been able to make it work... Halp! :)

I've already looked at: How to use a variable's value as another variable's name in bash and Dynamic variable names in Bash

Thanks!

Joe B
  • 11
  • 1
  • 4
  • Use [Shellcheck](https://www.shellcheck.net/) to find errors in your code. – pjh Mar 15 '22 at 23:52
  • It is possible to do what you are asking for, but it's messy and error-prone. There are often better ways. For instance, instead of using variables `char1`, `char2`, `...`, use an array called `chars`. For an improvement over `char_a`, `char_b`, `...`, use an associative array. See [Arrays -Bash Hackers Wiki](https://wiki.bash-hackers.org/syntax/arrays). – pjh Mar 15 '22 at 23:56
  • 1
    See [BashFAQ/006 (How can I use variable variables (indirect variables, pointers, references) or associative arrays?)](https://mywiki.wooledge.org/BashFAQ/006). – pjh Mar 16 '22 at 00:00
  • 1
    If you've read those duplicates, how do you _not_ know how to use `printf -v "char$1" %s "somevalue"`? – Charles Duffy Mar 16 '22 at 00:17
  • 1
    ...as for the reference end, it's `var="char$n"; echo "${!var}"` -- you have to do the indirect reference for the whole name at once, not just for the part that's dynamic. But again, this is already demonstrated in the existing duplicates. There are *lots* of different answers attached to _Dynamic variable names in bash_; I have trouble believing you read it thoroughly and came away not knowing a single working approach. – Charles Duffy Mar 16 '22 at 00:18
  • 1
    Thank you @pjh for your useful insights! I'm doing it as an array now, which is much simpler and the correct way to do what I need to do. – Joe B Mar 16 '22 at 23:21

0 Answers0