-1

I've seen this question asked before but I can't seem to get the grasp of it.

I have this variable that I get from user input read column_number

and then I join it with the "col" prefix to form the name of my variable

selected_column="col"$column_number

But when I try to evaluate it to get the result, I keep getting the (standard_in) 1: syntax error

sum=$(round $sum+"echo ${!selected_column}", 2)

full code:

Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46

1 Answers1

2
column_number=5
selected_column=col$column_number
col5=42
sum=17
echo $(($sum+${!selected_column}))

Output:

59

sum=$(round $(($sum+${!selected_column})) 2)
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Please could you give an explanation of `${!selected_column}` Is it the history expansion feature that we are using here? – sjsam Nov 29 '15 at 10:50
  • @sjsam: From `man bash`: "*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.*" – Cyrus Nov 29 '15 at 11:14
  • @gboffi : Wow !! Cheers pal !! Helped. – sjsam Nov 29 '15 at 11:14
  • Thank you!! it actually worked, although i had to tweak it a bit because it was interfering with the round function, so the actual usage (when it comes to the full code) is this: `sum=$(round $sum+${!selected_column} 2)` – Ángel Montes Nov 29 '15 at 12:52