0

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?

Nicolás Alarcón Rapela
  • 2,714
  • 1
  • 18
  • 29
Cedric
  • 245
  • 1
  • 12

2 Answers2

1

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Note that this only works for bash. zsh equivalent is `${(P)t}` – Ashwani Feb 03 '19 at 14:47
  • 2
    The question is only tagged `bash`. We don't need to provide the relevant syntax for every other shell. – chepner Feb 03 '19 at 14:49
  • Yes, you are right. But it will help someone who is working with zsh and came across this page while googling for the same problem. – Ashwani Feb 03 '19 at 14:54
0

A one-liner using eval to safely write a series of echos to output bash parameter transformation assignment statements, with GNU grep divvying up the input string:

h=foo o=bar
string() { eval $(printf 'echo ${%s@A};\n' $(grep -o . <<< "$@" )) ; }
string hello

Output, (blank lines represent the unset variables $e and $l):

h='foo'



o='bar'
agc
  • 7,973
  • 2
  • 29
  • 50