I am trying to make a script that takes a word and each letter up and turns it into a separate variable. My code currently does not work but I feel I just need to tweak one thing that I am unsure of.
(ex: if forum was typed in letter1=f; letter2=o; letter3=r;...)
Thank you
count=1;
for i in `echo $1 | sed 's/./& /g'`
do
echo $i
letter$count=$i
count=`expr $count + 1`
done
echo $var1
The following is kind of what you were going for, though Lakris' example above is why I come to this site, now I can spend Saturday examining the ${#var} (length of var ?)and ${var:$offset:$length} (substring ?) functions.
#!/bin/bash
for i in $(echo $1 | sed 's/./& /g'); do
letters[$count]=$i
count=$(($count+1))
done
for i in $(seq 0 $((${#letters[@]}-1))) ; do
echo $i letter is ${letters[$i]}
done
Looks good to me. What does your output look like?
$
$
$ cat -n var.sh
1 #!/bin/bash
2
3 for i in $(echo $1 | sed 's/./& /g'); do
4 letters[$count]=$i
5 count=$(($count+1))
6 done
7 for i in $(seq 0 $((${#letters[@]}-1))) ; do
8 echo $i letter is ${letters[$i]}
9 done
10
$
$
$ ./var.sh forum
0 letter is f
1 letter is o
2 letter is r
3 letter is u
4 letter is m
$
$
$ echo $SHELL
/bin/bash
$
$
Either that eval serves no purpose or that echo is unintended, but both of them together result in a pointlessly convoluted printing statement that is vulnerable to shell metacharacters.
echo "letter$x=${mystr:$((x-1)):1}" accomplishes the same thing in a safe, simple manner.
Anyone not using linux may find that their system does not have seq, a non-standard gnu tool. Also, the use of echo can be problematic. Aside from the lack of portability (not all echoes support the same options), if the value of the parameter expansion begins with a dash, it can cause problems. printf is a superior tool when dealing with unknown data.
To simply print out the letters one per line:
w=$word
while [ "$w" ]; do
printf %c\\n "$w"
w=${w#?}
done
To assign each letter to a variable whose name ends with an incrementing number (starting with 1):
w=$word i=0
while [ "$w" ]; do
eval "letter$((i+=1))=\${w%\$w{#?}}"
w=${w#?}
done