Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
BASH BASH!!! (need some shell scripting help)
#1
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?
Reply
#2
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
Reply
#3
that did it, thanks!
Reply
#4
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
$
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)