[BASH - KSH] Passing array to a function


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting [BASH - KSH] Passing array to a function
# 1  
Old 04-16-2008
[BASH - KSH] Passing array to a function

Passing a array to a function, a basic feature in modern language, seems to be only possible in KSH. Not in BASH. Depite all my efforts I couldn't come to a solution. See the following examples:

It works perfectly in KSH:
Code:
#!/usr/bin/ksh

function print_array {
    # assign array by indirect variable reference (namerefs)
    typeset -n array=$1

    # display array content
    echo "${array[*]}"
}

colors=('Pink' 'Light Gray' 'Green')

print_array "colors"

But this one gave me headhache:
Code:
#!/bin/bash

function print_array {
    # trying to assign array by indirect variable reference
    declare -a array=${!1}
    # local array=${!1}         # doesn't work either

    # display array content
    echo "${array[*]}"
}

colors=('Pink' 'Light Gray' 'Green')

print_array "colors"

Some reference in the manual for using indirect reference in BASH:
http://tldp.org/LDP/abs/html/bashver2.html#VARREFNEW
# 2  
Old 04-16-2008
This version works with ksh or bash.

Code:
#! /usr/local/bin/bash
#! /usr/bin/ksh

function print_array  {
        array_name=$1
        eval echo \${$array_name[*]}
        return
}

colors[0]="Pink"
colors[1]="Light Gray"
colors[2]="Green"

print_array colors
exit 0

# 3  
Old 04-17-2008
Hi Perderabo,

With my GNU bash, version 3.2.25 it only returns the array name "colors" but not its contents. I have also tried this trick:

Code:
function print_array {
    array_name="$1[*]"
    echo ${!array_name}
}

It returns the array elements (on one line) but the local array doesn't exists as such as I can not access it by doing something like:

Code:
function print_array {
    array_name="$1"
    echo ${!array_name[1]}
}

This always return the first element "pink" [0]. Of course I could access the array elements by doing:
Code:
function print_array {
    array_name="$1[0]"
    echo ${!array_name}

    array_name="$1[1]"
    echo ${!array_name}

    array_name="$1[2]"
    echo ${!array_name}
}

Which is rather inelegant and clumsy. All I wanted is to create a *local* copy of the array whose name is passed to the function as positional parameter ($1 $2 ....). By the way, how can I copy an array without looping throught it and assigning values one by one. Of course, the following doesn't work:
Code:
colors=('Pink' 'Light Gray' 'Green')
echo ${colors[@]}

copy_colors=$colors
echo ${copy_colors[@]}

# returns:
# Pink Light Gray Green (3 elements)
# Pink

copy_colors=(${colors[*]})
echo ${copy_colors[*]}
echo ${copy_colors[1]}

# "Light Gray" is split:
# Pink Light Gray Green (4 elements!)
# Light

I think I start to understand why members of this forum perfer ksh :=)

Last edited by ripat; 04-17-2008 at 08:21 AM..
# 4  
Old 04-17-2008
Boy, this one wasn't easy!

OK, here is what works in bash. Remember, the question was to pass an array to a function and make sure that whatever is done by the function remains local. If the local scope isn't necessary, just remove the "local" declaration.
Code:
#!/bin/bash

function print_array {
    # Setting the shell's Internal Field Separator to null
    OLD_IFS=$IFS
    IFS=''

    # Create a string containing "colors[*]"
    local array_string="$1[*]"

    # assign loc_array value to ${colors[*]} using indirect variable reference
    local loc_array=(${!array_string})

    # Resetting IFS to default
    IFS=$OLD_IFS

    # Checking the second element "Light Gray" (the one with a space)
    echo ${loc_array[1]}
    
}

# create an array and display contents
colors=('Pink' 'Light Gray' 'Green')
echo ${colors[*]}

# call function with positional parameter $1 set to array's name
print_array colors 

# checking whether the function "local" loc_array is visible here
echo "Does the local array exist here? -->${loc_array[*]}<--"
exit 0

This returns:
Code:
Pink Light Gray Green
Light Gray
Does the local array exist here? --><--

We can also "copy" an array the same way: setting IFS to NULL permit to do variable expansion that preserves the possible spaces in array's elements.
Code:
colors=('Pink' 'Light Gray' 'Green')
OLD_IFS=$IFS
IFS=''
copy_colors=(${colors[*]})
IFS=$OLD_IFS

echo ${copy_colors[*]}
echo ${copy_colors[1]}


Last edited by ripat; 04-18-2008 at 03:35 AM..
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Coredump when passing file name to ksh function

Hi, I'm playing with ksh. I'm trying to do a simple task: read file name from cli and call a function which calculated number of lines in file. I'm getting coredump every time when I try to read that file. Korn shell version $ print ${.sh.version} Version AJM 93u+ 2012-08-01 Main... (5 Replies)
Discussion started by: solaris_user
5 Replies

2. UNIX for Dummies Questions & Answers

Passing values from file into array in Bash

Hi, I'm trying to write a bash script that takes a file and passes each line from the file into an array with elements separated by column. For example: Sample file "file1.txt": 1 name1 a first 2 name2 b second 3 name3 c third and have arrays such as: line1 = ( "1" "name1" "a"... (3 Replies)
Discussion started by: ShiGua
3 Replies

3. Shell Programming and Scripting

Bash Passing An Array

Good grief so this should be easy. Passing an array as an argument to a function. Here is the sample code: #/bin/bash function foo { local p1=${1} local p2=(${2}) local p3=${3} echo p1 is $p1 echo p2 is $p2 echo p3 is $p3 } d1=data1 d2=data2 a=(bat bar baz) (2 Replies)
Discussion started by: brsett
2 Replies

4. Shell Programming and Scripting

Why double quotation marks doesn't work in ksh function parameters passing?

I'm working on AIX 6, ksh shell. The parameters are some strings quotated by double quotation marks which from a file. They are quotated because there may be spaces in them. Example: "015607" "10" " " "A"I want to pass these parameters to a shell function by writing the following command: ... (4 Replies)
Discussion started by: Shimmey
4 Replies

5. Programming

[solved]help passing array of structs to function in c

this is my code to try and prinnt out a deck of cards. the print function worked when used inside main without being a function but now i cant get it to work as a function probably since i dont know how to pass a struct array in c. I gave it a shot but i keep getting an assortment of errors. The... (0 Replies)
Discussion started by: bjhum33
0 Replies

6. Programming

Passing two dimensional array to a function

Hi. I have a problem with passing two dimensional array to a function. First, let me show my code to explain what i am going to do: I have function:void initialize_board(char board);which is supposed to modify content of passed array. I have read here: Question 6.18 how such arrays should be... (3 Replies)
Discussion started by: Shang
3 Replies

7. Shell Programming and Scripting

Passing array to functions in ksh script

Let me know if there is a way to pass array to a funtion in ksh script. function isPresent { typeset member member=$1 dbList=$2 echo '$1:' $1 echo '$2' $dbList The array will be at the second position....something like this isPresent 12 <array> if then echo... (3 Replies)
Discussion started by: prasperl
3 Replies

8. Shell Programming and Scripting

[bash] passing array to function

Hi, I'm trying to write a function that reassigns an array to another local array but the method used in reassigning the array reformats the contents of the array which is what I am trying to prevent. The method used to load a file into an array works as expected and the entire array is... (4 Replies)
Discussion started by: ASGR
4 Replies

9. Shell Programming and Scripting

passing values to function in Ksh

Hi, I'm trying to work on the script given below #!/bin/ksh -x pfile() { echo "$1" } touch smp19 echo "Hi" > smp19 result=$(pfile $smp19) echo $result As highlighted , when i pass $smp19 as parameter ,it does not display the output.However when i try giving "Hi" instead... (2 Replies)
Discussion started by: Sheema
2 Replies

10. Shell Programming and Scripting

Perl Function Array Arguement Passing

Hi All, I have some questions regarding array arguements passing for Perl Function. If @array contains 2 items , arguements passing would be like Code_A. But what if @array needs to add in more items, the rest of the code like $_ will have to be modified as well (highlighted in red), which is... (5 Replies)
Discussion started by: Raynon
5 Replies
Login or Register to Ask a Question