|
Home > Archive > Unix Shell > February 2006 > Variable name as function's argument
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 |
Variable name as function's argument
|
|
| spamkit@gmail.com 2006-02-20, 8:49 pm |
| Hi,
I would like to construct the following: I've a number of arrays in my
bash script like ARRAY1, ARRAY2, ARRAY3 and I've a number of functions
which are used to perform multiple array operations. Now I would like
to call functions with argument containing array variable names. How do
I access arrays inside the func?
Example:
#!/bin/sh
ARRAY1[1]=1
ARRAY1[2]=2
ARRAY2[1]=10
ARRAY2[2]=11
function dosomethingonarray()
{
... Now I must know how to access array values here ...
}
# Perform operation on array
dosomethingonarray "ARRAY1" # let's do that on array 1
dosomethingonarray "ARRAY2" # let's do that on array 2
Thanks in ahead
| |
| Xicheng 2006-02-21, 2:49 am |
| spamkit@gmail.com wrote:
> Hi,
>
> I would like to construct the following: I've a number of arrays in my
> bash script like ARRAY1, ARRAY2, ARRAY3 and I've a number of functions
> which are used to perform multiple array operations. Now I would like
> to call functions with argument containing array variable names. How do
> I access arrays inside the func?
>
> Example:
>
> #!/bin/sh
>
> ARRAY1[1]=1
> ARRAY1[2]=2
> ARRAY2[1]=10
> ARRAY2[2]=11
>
> function dosomethingonarray()
> {
> ... Now I must know how to access array values here ...
> }
>
> # Perform operation on array
> dosomethingonarray "ARRAY1" # let's do that on array 1
> dosomethingonarray "ARRAY2" # let's do that on array 2
>
ARRAY1=(a1 a2 a3)
ARRAY2=(b1 b2 b3)
dosomethingonarray() {
for i in $( eval echo \${$1[@]} ); do
echo $i
done
}
dosomethingonarray ARRAY1
echo "-----------"
dosomethingonarray ARRAY2
====result=====
a1
a2
a3
-----------
b1
b2
b3
=============
Best,
Xicheng
| |
| Chris F.A. Johnson 2006-02-21, 5:54 pm |
| On 2006-02-21, spamkit@gmail.com wrote:
> Hi,
>
> I would like to construct the following: I've a number of arrays in my
> bash script like ARRAY1, ARRAY2, ARRAY3 and I've a number of functions
> which are used to perform multiple array operations. Now I would like
> to call functions with argument containing array variable names. How do
> I access arrays inside the func?
>
> Example:
>
> #!/bin/sh
>
> ARRAY1[1]=1
> ARRAY1[2]=2
> ARRAY2[1]=10
> ARRAY2[2]=11
>
> function dosomethingonarray()
> {
> ... Now I must know how to access array values here ...
> }
>
> # Perform operation on array
> dosomethingonarray "ARRAY1" # let's do that on array 1
> dosomethingonarray "ARRAY2" # let's do that on array 2
Use "${ARRAY[1]}", not ARRAY1.
--
Chris F.A. Johnson, author | <http://cfaj.freeshell.org>
Shell Scripting Recipes: | My code in this post, if any,
A Problem-Solution Approach | is released under the
2005, Apress | GNU General Public Licence
|
|
|
|
|