I have attempted to create an array consisting of two items: #0 and #1.
I am able to print the two items corrctly:
arr=(hello "my name is")
echo ${arr[0]}
hello
echo ${arr[1]}
my name is
However, when I try to run a for loop to print both objects:
for i in ${arr
[*]}
do
echo $i
done
I get:
hello
my
name
is
If there are two objects, why is the output on four lines? How do I loop on two lines?
My goal is to get:
hello
my name is
The problem is the behavior of the "for"-loop in connection with an obvious misunderstanding about what "${arr[*]}" means.
The subscript "*" in an array denotes ALL array elements and it is expanded before the for-loop is executed. Therefore this is what the shell "sees":
for i in ${arr[*]} # original line, begin of parsing process
for i in hello my name is # after expanding the variables
Now, "$i" is assigned one word each pass of the for-loop because this is how this kind of loop behaves. There are two possibilities to correct this:
- Use a while-loop instead:
echo ${arr[*]} | while read a ; do
echo $a
done
- Instead of using this faulty way of expanding the array count elements:
i=1
for i in {1..${#arr[*]}} ; do
echo ${arr[$i]}
done
"${#arrayname[*]}" expands to the number of elements in your array (instead of the whole array itself), in your case: 2.
I hope this helps.
bakunin
rdrtx1
3
try also:
arr=(hello "my name is")
echo ${arr[0]}
echo ${arr[1]}
for i in "${arr[@]}"
do
echo $i
done