Search code examples
bashparameter-expansion

Why bash indirect expansion has to use temp variable?


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?


Solution

  • 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.)