You need eval
with echo
i.e. you need to evaluate the expansion, not output it:
eval echo $a$(($#-i))
Note that, using eval
in general is discouraged as this could result in security implications if the input string is not sanitized. Check John1024's answer to see how this can be done without eval
.