Search code examples
bashparameter-expansion

Value of var is not shown when concatenating $ and var --> $var


I've got about a day of experience in bash as of now..

string () {
    for (( i=0; i<${#1}; i++ ))
    do
        echo "$"${1:$i:1}""
    done
}


string "hello"

This script returns "$h", "$e", "$l", "$l", "$o", but I actually want it to return the contents of variables h, e, l, l and o.

How do I do that?


Solution

  • You need to use indirect parameter expansion:

    for ((i=0; i<${#1}; i++)); do
        t=${1:i:1}
        echo "${!t}"
    done
    

    ${!t} takes the value of $t, and treats that as the name of the parameter to expand.