Posts: 37,105
Threads: 2,599
Joined: May 2025
Reputation:
0
My foray into shell scripting has been successful so far but i'm hitting a problem using an array of strings.
array="1 2 3"
for i in $array
do
echo $i
done
will print
1
2
3
but
array=( "Backup One" "Backup Two" )
only prints the first item, although the length of the array correctly returns 2 - ${#array[@]}
any ideas?
Posts: 4,930
Threads: 69
Joined: May 2025
Try
echo ${array[0]}
echo ${array[1]}
and you will find that the assignments are being made correctly. It is the 'for' loop that isn't doing what you need.
#!/bin/sh
declare -a array
array=( "Backup One" "Backup Two" )
element_count=${#array[@]}
index=0
while [ "$index" -lt $element_count ]
do
echo ${array[$index]}
let "index = $index + 1"
done
Posts: 5,314
Threads: 111
Joined: May 2025
The for ... in ... ; do ... ; done
form will work just fine, BTW :
$ declare -a array
$ array=( Backup One
Backup Two
)
$ for i in ${array[@]}
; do echo $i; done
Backup One
Backup Two
$
The quotes around ${array[@]} are required to preserve whitespace embedded in each array element. Without the quotes, the shell uses whitespace as a word separator, and the list will have four elements:
$ declare -a array
$ array=( Backup One
Backup Two
)
$ for i in ${array[@]} ; do echo $i; done
Backup
One
Backup
Two
$