shell : convert string to array

<<< is a zsh operator now supported by a few other shells (including bash).

read -a is bash-specific. ksh had read -A for that long before bash (consistent with set -A; set -a being something else inherited from the Bourne shell; also supported by zsh and yash)

sh these days is an implementation or another of an interpreter for the POSIX sh language. That language has neither <<< nor read -a nor arrays (other than "[email protected]").

On Ubuntu, by default, the shell used as sh interpreter is dash which is very close to the POSIX sh specification in that it implements very few extensions over what POSIX specifies. It implements none of <<<, read -a nor arrays.

In POSIX sh, to split a string into the one POSIX sh array ("[email protected]"), you'd use:

IFS=.             # split on .
set -o noglob     # disable glob
set -- $VERSION"" # split+glob with glob disabled.
echo "$# elements:"
printf ' - "%s"\n' "[email protected]"

It has a few advantages over the bash-specific IFS=. read -a <<< $string syntax:

  • it doesn't need creating a temporary file and storing the contents of $string in it.
  • it works even if $string contains newline characters (read -a <<< $string) would only read the first line.
  • it works even if $string contains backslash characters (with read, you need the -r option for backslash not to undergo a special processing).
  • it's standard.
  • it works for values like 1.2.. read -a <<< $string would split it into "1" and "2" only instead of "1", "2" and "".
  • in older versions of bash, you had to quote the $string (IFS=. read -ra <<< "$string") or otherwise it would undergo splitting (followed by joining with space).

You're hashbang is /bin/sh and you are running the script with sh, which does not support the <<< herestring. If you use /bin/bash it will work.

Additionally, while /bin/sh often supports arrays it is not required to do so, if an array is required you should use ksh, bash, zsh, or another shell that has support for them.