|
|||||||
| Forums | Search Forums | Register | Forum Rules | Man Pages | Albums | FAQ | Members | Calendar | Search | Today's Posts | Mark Forums Read |
| UNIX for Dummies Questions & Answers If you're not sure where to post a UNIX or Linux question, post it here. All UNIX and Linux newbies welcome !! |
|
|
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Array question
I have attempted to create an array consisting of two items: #0 and #1. I am able to print the two items corrctly: Code:
arr=(hello "my name is")
echo ${arr[0]}
hello
echo ${arr[1]}
my name isHowever, when I try to run a for loop to print both objects: Code:
for i in ${arr[*]}
do
echo $i
doneI get: Code:
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: Code:
hello my name is |
| Sponsored Links | ||
|
|
#2
|
|||
|
|||
|
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": Code:
for i in ${arr[*]} # original line, begin of parsing process
for i in hello my name is # after expanding the variablesNow, "$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: 1. Use a while-loop instead: Code:
echo ${arr[*]} | while read a ; do
echo $a
done2. Instead of using this faulty way of expanding the array count elements: Code:
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 |
| Sponsored Links | ||
|
|
#3
|
|||
|
|||
|
try also: Code:
arr=(hello "my name is")
echo ${arr[0]}
echo ${arr[1]}
for i in "${arr[@]}"
do
echo $i
done |
| Sponsored Links | ||
|
![]() |
| Tags |
| echo |
| Thread Tools | Search this Thread |
| Display Modes | |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| array question | sacat | Programming | 2 | 01-31-2011 03:32 PM |
| Help! Yet another check element in array Question | alan | Shell Programming and Scripting | 2 | 07-29-2010 10:57 AM |
| Array question | ahtat99 | Shell Programming and Scripting | 4 | 09-11-2006 08:15 AM |
| Array question | TheCrunge | UNIX for Dummies Questions & Answers | 2 | 02-23-2005 04:55 PM |
| Storage array question | ncmurf00 | Filesystems, Disks and Memory | 1 | 11-25-2002 03:25 PM |
|
|