1

From https://stackoverflow.com/a/10820494/1764881, I know that the standard way of doing it seems to be:

   var="SAMPLE$i"
   echo ${!var}

But, I can't seem to do any of these following forms. They all failed:

echo ${!SAMPLE$i}
echo ${!"SAMPLE$i"}

I read the bash man page, but I still couldn't understand. Is it true that the first form is the only form accepted?

Community
  • 1
  • 1
Boyang
  • 2,520
  • 5
  • 31
  • 49
  • "Why did language X make decision Y?" is a question for the folks who designed the language (mostly, David Korn, since this syntax originated with ksh), and arguably too broad to be a good fit here. "Is it unconditionally true that language X enforces decision Y?", by contrast, is a question to which a simple, concise answer is available: In this case, yes. – Charles Duffy Feb 09 '16 at 16:57

1 Answers1

2

Yes. The underlying logic is that all parameter expansions take a single, literal word as the name of the parameter to expand, and any additional operator does something to the result. ! is no exception; var is expanded as usual, but the result is expanded again.

(As an aside, even arrays follow this rule. It might seem that something like ${array[2]%foo} applies two operators to array, but really array[2] is treated as the name of a single parameter. There is a little difference, as the index is allowed to be an arbitrary arithmetic expression rather than a literal number.)

(And for completeness, I should mention the actual exceptions, ${!prefix*} and ${!name[*]}, which confusingly use the same operator ! for querying variables themselves. The first lists variable names starting with the same prefix; the second lists the keys of the named array.)

chepner
  • 497,756
  • 71
  • 530
  • 681