This is my simple shell script. The objective is to split string "RANDOM948" as array so that I can manipulate any character in string "RANDOM948".
ubuntu@Ubuntu:~$ cat -n longscript.sh
1 string="RANDOM948"
2
3 c1=${string:0:1}
4 c2=${string:1:1}
5 c3=${string:2:1}
6 c4=${string:3:1}
7 c5=${string:4:1}
8 c6=${string:5:1}
9 c7=${string:6:1}
10 c8=${string:7:1}
11 c9=${string:8:1}
12
13 echo $c9 $c4 $c1
ubuntu@Ubuntu:~$
ubuntu@Ubuntu:~$ ./longscript.sh
8 D R
ubuntu@Ubuntu:~$
I believe this can be simplify by using for loop. This is my attempt. However, I have no idea how to save the loop output as array.
ubuntu@Ubuntu:~$ cat -n testscript.sh
1 string="RANDOM948"
2
3 for i in {1..9}
4 do
5 echo c$i=$\{string:`expr $i - 1`:1}
6 done
7
8 # echo $c9 $c4 $c1
ubuntu@Ubuntu:~$
ubuntu@Ubuntu:~$ ./testscript.sh
c1=${string:0:1}
c2=${string:1:1}
c3=${string:2:1}
c4=${string:3:1}
c5=${string:4:1}
c6=${string:5:1}
c7=${string:6:1}
c8=${string:7:1}
c9=${string:8:1}
ubuntu@Ubuntu:~$
UPDATE: New code as advised by @sos
I've updated this code with new line (5 & 6), however it still doesn't work
ubuntu@Ubuntu:~$ cat -n testscript.sh
1 string="RANDOM948"
2
3 for i in {1..9}
4 do
5 typeset -a c
6 c[${i}]=$\{string:`expr $i - 1`:1}
7 done
8
9 echo TEST OUTPUT $c9 $c4 $c1
ubuntu@Ubuntu:~$
ubuntu@Ubuntu:~$
ubuntu@Ubuntu:~$ ./testscript.sh
TEST OUTPUT
ubuntu@Ubuntu:~$