how to pass a value to a variable that in a other variable

I am getting a “bad substitution” error while running this code. I want to print the values in h_1, h_2, h_3with a for loop.

#/!/bin/bash
h_1=12
h_2=13
h_3=14
for ((i=1; i<=2; i++))
 do
  echo "${h_$i}"
done

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You need to use indirect parameter expansion with !:

tmp=h_$i
echo "${!tmp}

You have to make the extra tmp variable here – you can’t just use a string, unfortunately. Indirect expansion works as follows:

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.

So, above, ${!tmp} expands to the value of the variable whose name is given by the value of the variable tmp.

It’s also possible to use eval here, but the indirection approach is tidier.

Method 2

I would use double parentheses form, the so called Arithmetic Expansion:

echo $((h_$i))

No need of arrays, temporary variables or other fancy stuff. Also, I believe this form is most portable (arithmetic expansion is require by POSIX as far as I know).

From Bash Manual:

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:

          $((expression))

The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, string expansion, command substitution, and quote removal. Arithmetic expansions may be nested.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x