0

I am working on a project where variables need to be assigned according to number contained in a certain file. I feel it may be pointless to include and explain all the code, so I have reduced the question to one involving a simple example.

for ((i=1; i<=3; i++));
do
    align_$i=100_$i
done

In this example code, I am getting the following error (among the other 2):

line 3: align_1=100_1: command not found

so I know my method substitution is working, but it is not recognized as a correct assignment. I am clearly making a simple mistake but really have no clue how to solve this.

A little bit of a different idea: I am having an issue calling the value of variable where the variable is doubly dependent on the looping variable. So, using the supposed correct output from the example above, if I were in another loop where I need to call align_1's value, but need to do so like

for ((i=1; i<=3; i++));
    do something with $align_$i

how would I properly do this? Using these variables must be in another loop, otherwise I wouldn't have this problem!

I apologize for a simple question-- Bash is not a strength of mine.

Thank you

2
  • 1
    This is arguably a duplicate of our many, many questions on indirect assignment and/or expansion. Commented Aug 28, 2017 at 20:31
  • See in particular BashFAQ #6. Commented Aug 28, 2017 at 20:32

1 Answer 1

2

Best Answer: Don't

The need for this can generally be avoided if you use an array (or an associative array with non-numeric keys):

align=( )
for ((i=1; i<=3; i++)); do
    align[$i]="100_$i"
done

But if you must...

On bash 4.3+

A namevar allows full, bidirectional access (both read and write) under an aliased variable name; alias targets can be of any type, including arrays themselves:

for ((i=1; i<3; i++)); do
    declare -n align_var="align_$i"
    align_var="100_$i"
    unset -n align_var
done

On older releases

...and if you don't have bash 4.3 or later, use printf -v:

for ((i=1; i<3; i++)); do
    printf -v "align_$i" %s "100_$i"
done
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, despite the duplicate question! You're helping a novice Bash programmer find leukemia-linked genes :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.