TL;DR: this is just to see if it can be done. Use fold
like anubhava suggests; starting a single process is a small price to pay to avoid not one, but two uses of eval
.
I wouldn't actually use this (I think it's safe, but I wouldn't swear to it, and boy, is it ugly!), but you can use eval
, brace expansion, and substring parameter expansion to accomplish this.
$ temp=hello
$ arr=( $(eval echo $(eval echo \\\${temp:{0..${#temp}}:1})) )
$ printf '%s\n' "${arr[@]}"
h
e
l
l
o
How does this work? Very delicately. First, the shell expands ${#temp}
to the length of the variable whose contents we want to split. Next, the inner
eval turns the string \${temp:{0..5}:1}
into a set of strings ${temp:0:1}
, ${temp:1:1}
, etc. The outer eval
then performs the parameter expansions that produce one letter each from temp
, and those letters provide the contents of the array.