On the topic of BASH loops

Chris F.A. Johnson c.f.a.johnson-bJEeYj9oJeDQT0dZR+AlfA at public.gmane.org
Thu Aug 19 19:07:32 UTC 2004


On Thu, 19 Aug 2004, Paul King wrote:

> The recent discussion got me thinking about BASH loops. I use them ad nauseam
> to download radio programs of certain dates and times from radio station
> archives (such as Pacifica).
>
> The biggest issue for me was that if I had multiple dates, I could not place
> them in an array. For example:
>
> dates=("Mon Aug 16" "Tue Aug 17" "Wed Aug 18")
>
> for i in ${dates[@]} ; do

      You forgot the quotes:

for i in "${dates[@]}" ; do

>    echo ${i}
> done
>
> gives me the same output as if I had declared my array as:
>
> dates='Mon Aug 16 Tue Aug 17 Wed Aug 18'
>
> for i in $dates ; do
>    echo ${i}
> done
>
> OUTPUT:
> Mon
> Aug
> 17
> Tue
> Aug
> 17
> Wed
> Aug
> 18
>
> YECCH!
>
> The only way I could declare a BASH array in any useful sense is to do it
> explicitly (as taken from a script that just ran successfully):
>
> date[1]='Mon 2004 08 16'
> date[2]='Tue 2004 08 17'
> date[3]='Wed 2004 08 18'
>
> for i in 1 2 3 ; do
>   echo ${date[$i]}
> done
>
> OUTPUT:
> Mon 2004 08 16
> Tue 2004 08 17
> Wed 2004 08 18
>
> Much better!

    Or:

printf "%s\n" "${date[@]}"

> Notice I could have used any three index values that darned well pleased me. If
> anyone can come up with a better way in BASH to declare an array of strings
> which have whitespace in them, please suggest something.

     The method you use to store them in the array is irrelevant. You
     get the ouput you want if you use quotes.

     You can also add elements to the array with:

unset date
date[${#date[@]}]='Mon 2004 08 16'
date[${#date[@]}]='Tue 2004 08 17'
date[${#date[@]}]='Wed 2004 08 18'

-- 
 	Chris F.A. Johnson                      http://cfaj.freeshell.org
 	=================================================================
                 Everything in moderation -- including moderation
--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml





More information about the Legacy mailing list