Unix Shell - dereferencing bash array elements

This is Interesting: Free IT Magazines  
Home > Archive > Unix Shell > October 2006 > dereferencing bash array elements





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author dereferencing bash array elements
osiris@abydos.kmt

2006-10-21, 1:31 pm

Why does this dereference properly?

printf "%s" "${PATH_ARRAY[$J]}"


but this does not?

printf "%24s%s%s\n" '<option value="' "${JPEG_ARRAY[$J]}" '"></option>'


In the log that I create of the script using:

bash -x myscript > /tmp/mylog 2>&1

I see the values get assigned to array properly (see 'sed' line below)
yet dereferencing the array element fails.

Below is the assignment:

# Load the array with the filename of each JPEG in the folder
J=1
find . -maxdepth 1 -name "*.jpg" |
{
while read JPEG ; do
JPEG_ARRAY[$J]=`echo "$JPEG" |sed 's/\.\///g'`
J=$(( $J + 1 )) # increment J
echo "${JPEG_ARRAY[$J]}"
done
}

The echo even returns null. I've poured over it but
I just can't see what I'm doing wrong. Thanks for any help.
Chris F.A. Johnson

2006-10-21, 7:31 pm

On 2006-10-21, osiris@abydos.kmt wrote:
> Why does this dereference properly?
>
> printf "%s" "${PATH_ARRAY[$J]}"
>
>
> but this does not?
>
> printf "%24s%s%s\n" '<option value="' "${JPEG_ARRAY[$J]}" '"></option>'


Variables inside single quotes are not expanded.

> In the log that I create of the script using:
>
> bash -x myscript > /tmp/mylog 2>&1
>
> I see the values get assigned to array properly (see 'sed' line below)
> yet dereferencing the array element fails.
>
> Below is the assignment:
>
> # Load the array with the filename of each JPEG in the folder
> J=1
> find . -maxdepth 1 -name "*.jpg" |
> {


The braces are unnnecessary.

> while read JPEG ; do
> JPEG_ARRAY[$J]=`echo "$JPEG" |sed 's/\.\///g'`


Use parameter expansion rather then sed:

JPEG_ARRAY[$J]=${JPEG#./}

> J=$(( $J + 1 )) # increment J
> echo "${JPEG_ARRAY[$J]}"


You have incremented $J to an unassigned index. Put the echo (or,
better still, use printf) before you increment J.

> done
> }
>
> The echo even returns null. I've poured over it but
> I just can't see what I'm doing wrong. Thanks for any help.



--
Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com