How to convert a string into an array of individual characters in Bash?

advertisements

How do I take a string, something simple like "Hello World!" and split it into its individual characters?

Using the example above, I want an array with a single character put into each value. So the array's internals would end up looking like:

{"H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d", "!"}


str="Hello world!"
for (( i=0 ; i < ${#str} ; i++ )) {
    arr[$i]=${str:i:1}
}

#print
printf "=%s=\n" "${arr[@]}"

output

=H=
=e=
=l=
=l=
=o=
= =
=w=
=o=
=r=
=l=
=d=
=!=

You can assign into array the result of any command using the

mapfile -t array < <(command args)

Unfortunately, defining the custom delimiter -d needs bash 4.4.+. Let say, want break the above string into 2 char pieces - using grep

mapfile -t -d ''  a2 < <(grep -zo .. <<<"$str")
printf "=%s=\n" "${a2[@]}"

output:

=He=
=ll=
=o =
=wo=
=rl=
=d!=