This script shows how to split a colon-separated string into a Bash array.
#!/usr/bin/env bash
words="france-country:Italy-country:singapore-country:Australia-country"
IFS=':' array1=($words)
numwords="${#array1[@]}"
for((i=0; i<numwords; i++));do
echo "$i: ${array1[i]}"
done
output
0: france-country
1: Italy-country
2: singapore-country
3: Australia-country
Note that in
array1=($words)
we don't put quotes around $words
, as that would prevent word splitting.
We don't actually need the quotes in
words="france-country:Italy-country:singapore-country:Australia-country"
but quotes (either single or double) would be needed if there were any spaces in that string. Similarly, the quotes are superfluous in numwords="${#array1[@]}"
, and many Bash programmers would omit them because we know the result of ${#array1[@]}
will never have spaces in it.
It's a Good Idea to always use quotes in Bash unless you're sure you don't want them, eg in the case of array1=($words)
above, or when performing tests with the [[
... ]]
syntax.
I suggest you bookmark BashGuide and browse through their FAQ. But the only way to really learn the arcane ways of quoting and splitting in Bash is to to write lots of scripts. :)
You may also find ShellCheck helpful.