About split a string into an array we have two scenarios:
if the string has empty spaces how a separator, according with the following post:
So If I use:
string="Hello Unix World"
array1=($string)
echo ${array1[@]}
echo "size: '${#array1[@]}'"
read -a array2 <<< $string
echo ${array2[@]}
echo "size: '${#array2[@]}'"
The output is:
Hello Unix World
size: '3'
Hello Unix World
size: '3'
Both approaches works as expected.
Now, if the string has something different than an empty space how a separator, according with the following post:
So If I use:
path="/home/human/scripts"
IFS='/' read -r -a array <<< "$path"
echo "Approach 1"
echo ${array[@]}
echo "size: '${#array[@]}'"
echo "Approach 2"
for i in "${array[@]}"; do
echo "$i"
done
echo "Approach 3"
for (( i=0; i < ${#array[@]}; ++i )); do
echo "$i: ${array[$i]}"
done
It prints:
Approach 1
home human scripts <--- apparently all is ok, but see the line just below!
size: '4'
Approach 2
<--- an empty element
home
human
scripts
Approach 3
0: <--- confirmed, the empty element
1: home
2: human
3: scripts
Why appears that empty element? How fix the command to avoid this situation?
/is the delimiter this -/home/human/scripts- has 4x fields ... the empty string before the first/, and the other 3 fields that you know about; if the input was//home/human/scripts/you'd have 6 fields ... 2 empty strings +home+human+scripts+ 1 empty stringecho "${array[@]}"would have output ` home human scripts, with the space separating the empty string fromhome` visible. Without quotes,echoreally does only get three arguments; the unquoted empty string "vanishes" during word-splitting.cutandawk) or that useIFSto split the input (eg,read- see konsolebox's example)echo "${array[@]}"comes fromechoitself, not the array.