0

I am trying to split letters from a word and print them in new line using the following method. But I am not able to assign values to the variable. Correct me if I am missing any fundamental rule here.

stringOneLength=$(echo `expr length $1`)
echo $stringOneLength
stringTwoLength=$(echo `expr length $2`)

echo $stringTwoLength


for ((i=1; i<=$stringTwoLength; i++)) ;
do
    x$i=$(echo "$1" | sed 's/\(.\{1\}\)/\1 /g' | sed 's/\(.\{1\}\)/\1 /g' |awk '{print $i}')

    echo x$i
done

Getting following error:

sh FileName one two
3
3
samp: line 13: x1=o: command not found
x1
samp: line 13: x2=o: command not found
x2
samp: line 13: x3=o: command not found
x3

What is wrong with my approach and how can I fix my variable assignment?

1 Answer 1

1

It looks like you're trying to dynamically create variable names using $i. Firstly, I would recommend against this if possible - it would be better to use an array if your shell supports it. However, it can be done using eval:

eval x$i=$( ... )

Using eval, the $i is expanded before the assignment takes place.

Using bash, there's also declare, which you can use instead of eval. It deservedly has a better reputation than eval as it is safer. However, if you're using bash, you can (and should) use an array instead:

x=() # before the loop
x[i]=$( ... )

It's also worth mentioning that if you don't actually need to store each value separately (i.e. you don't plan on using them later on), you can just remove the $i entirely and do a simple assignment in the loop:

x=$( ... )
Sign up to request clarification or add additional context in comments.

Comments