The problem is your array. It seems that you have created an array with only one element. Try this example:
array=("$(printf 'Apple\nBanana\nClementine\nDate')")
for ((i = 0; i < ${#array[@]}; i++)); do
printf '%d. %s\n' $((i+1)) "${array[$i]}"
done
j=0
for e in "${array[@]}"; do
j=$((j+1))
printf '%d. %s\n' "$j" "$e"
done
k=0
for e in ${array[@]}; do
k=$((k+1))
printf '%d. %s\n' "$k" "$e"
done
Then run:
$ ./test.sh
1. Apple
Banana
Clementine
Date
1. Apple
Banana
Clementine
Date
1. Apple
2. Banana
3. Clementine
4. Date
You can see, you actually create an array contains one element. The 3rd loop print four elements because the shell had performed field splitting on string Apple\nBanana\nClementine\nDate
, which gave you four separated words back.
If you change the array to:
set -f
array=( $(printf 'Apple\nBanana\nClementine\nDate') )
set +f
(set -f
disables wildcard expansion, in case the characters *?\[
appear in the output of the command) you will get the desired result, which is that the output of the command is split at whitespace:
$ ./test.sh
1. Apple
2. Banana
3. Clementine
4. Date
1. Apple
2. Banana
3. Clementine
4. Date
1. Apple
2. Banana
3. Clementine
4. Date
A note that you must use double quotes "${array[@]}"
when you want to iterate through all array elements, or use the c-style for loop like my first example.