Search code examples
shellshposix

posix sh: is it possible to iterate through a string without using an external tool?


In POSIX sh, I am able to iterate through each character in a string using a while loop and cut; here is a demonstration:

#!/bin/sh

lizards='geckos,anoles'

string_length="${#lizards}"

i=1
while [ "$i" -le "$string_length" ]; do
    char="$(echo "$lizards" | cut -c "$i")"
    echo "$char"
    i="$(( i + 1 ))"
done

Output is:

g
e
c
k
o
s
,
a
n
o
l
e
s

Is there a way I can do without this having to call an external command?


Solution

  • You can use printf to get the first character and parameter expansion to remove it:

    #!/bin/sh
    
    lizards='geckos,anoles'
    
    while [ -n "$lizards" ]; do
        printf '%.1s\n' "$lizards"
        lizards="${lizards#?}"
    done