Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

ksh function return array

247 views
Skip to first unread message

reuben26

unread,
Apr 8, 2009, 3:22:06 PM4/8/09
to
How do i return an array from a ksh utility function and use the array
in my ksh script?

I tried doing a "return <array name>" in the function and tried a

set -A arr `func1`

but it did not work.

The array elements have space delimited data. So it is important that
i use an array and not a string.

This script runs on a linux box.

Please let me know.

Thanks,
Reuben.

Jon LaBadie

unread,
Apr 8, 2009, 3:54:20 PM4/8/09
to

"return" only can only be used to return a single numeric value

Seems to me that the array should also be visible outside the
function unless you have declared it local to the function
(such as doing a "typeset -A arr")

an alternative to the return <arr> would be to print it to
stdout and capture the function output with command substitution

var=$(func1 <args>)

Barry Margolin

unread,
Apr 8, 2009, 4:20:11 PM4/8/09
to
In article <Mh7Dl.2440$6n....@nwrddc01.gnilink.net>,
Jon LaBadie <jXla...@aXcm.oXrg> wrote:

He pointed out the problem with that: the array elements can contain
spaces. When you do this, you lose the distinction between the spaces
separating the elements and the spaces within the elements.

If there's some character that can never appear within an element, you
can use that as the element separator when your function prints its
results. Then the caller can do:

IFS=<char>
set -A arr `func1`

--
Barry Margolin, bar...@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
*** PLEASE don't copy me on replies, I'll read them in the group ***

OldSchool

unread,
Apr 8, 2009, 4:23:21 PM4/8/09
to
"Seems to me that the array should also be visible outside the
function unless you have declared it local to the function
(such as doing a "typeset -A arr")"

right...as in this works (with or without the typeset)

#!/bin/bash

typeset -a arr

function myf {
arr[1]=a
arr[2]=b
echo ${arr[@]}
}


myf
echo ${arr[@]}

while this doesn't (as the array scoped inside the function)


#!/bin/bash


function myf {
typeset -a arr
arr[1]=a
arr[2]=b
echo ${arr[@]}
}


myf
echo ${arr[@]}
~


for a real treat.....

#!/bin/bash

typeset -a arr
arr[1]=Z
arr[2]=X

function myf {
typeset -a arr
arr[1]=a
arr[2]=b
echo ${arr[@]}
}


myf
echo ${arr[@]}


which illustrates the scoping

0 new messages