Hello everybody!
Why I can export arrays in ksh?
I trie this for exemplo:
In parent script
array[0]=a
array[1]=b
array[2]=c
export array
When I see the variable array in child script there are only first index.
For exemplo in child script
+echo ${array[*]}
a
But I want all index.
Any idea?
Arrays cannot be exported the same way variables can be. This is a known limitiation in Korn Shell. You can export every single array element (by using the array name this is the first element by default, as you have already experienced), but not the array itself.
Either you do something like:
(( iCnt = 0 ))
while [ $iCnt -lt ${array[*]} ] ; do
export array[$iCnt]
(( iCnt += 1 ))
done
or you do a little trick: you can pass the arrays name as a parameter to a subroutine, yes? Then use eval to copy the array into a local array. Here is an example:
function pShowArray
{
typeset chArrayName="$1"
typeset -i iCnt=0
(( iCnt = 0 )) # copy array into local (to the function) array
while [ $iCnt -le $(eval print \${#$1[*]}) ] ; do
typeset aLocalArray[$iCnt]=$(eval print - \${$1[$iCnt]})
(( iCnt += 1 ))
done
print - "The passed array is named: $chArrayname"
print - "It has ${#aLocalArray[@]} elements, which are:"
(( iCnt = 0 ))
while [ $iCnt -le ${#aLocalArray[@]} ] ; do
print - "Element #${iCnt} is \"${aLocalArray[$iCnt]}\""
(( iCnt += 1 ))
done
return 0
}
# ---- function main
typeset aArrOne[0]="foo"
typeset aArrOne[1]="bar"
typeset aArrOne[2]="wee"
typeset aArrOne[3]="duh"
typeset aArrTwo[0]="1"
typeset aArrTwo[1]="2"
typeset aArrTwo[2]="3"
pShowArray aArrayOne
pShowArray aArrayTwo
exit 0
I hope this helps. It is somewhat like passing parameters via a pointer instead of passing them directly, isn't it?
bakunin
You cannot export arrays.
The easiest way to pass an array is to convert it to a scalar variable, with the elements separated by a character not used in any of the elements. For example, this uses a newline:
array_separator='
' ## adjust as needed
array=( a b c )
array_contents=$( printf "%s$array_separator" "${array[@]}" )
export array_separator array_contents
To convert it back to an array:
oIFS=$IFS
IFS=$array_separator
array=( $array_contents )
IFS=$oIFS
bakunin and cfajohnson thank you so much for your helps.