How to pass and read an array in ksh shell script function.?

I'm able to read & print an array in varaible called "filelist"

I need to pass this array variable to a function called verify() and then read and loop through the passed array inside the function.

Unfortunately it does not print the entire array from inside the funstion's loop.

#/bin/ksh
set -A filelist val1 val2 val3
set -A FList

verifyfiles()
{
FList="${1[@]}"

for sym in "${FList[@]}"
do
echo "Array in FUNCTION Contains:"
    echo "$sym"
done
}

verifyfiles $filelist

The first posistional parameter is NOT an array, and thus can't be indexed.

How about

verifyfiles() {  for sym ; do echo "Array in FUNCTION Contains:";     echo "$sym"; done; }
.
.
.
verifyfiles ${filelist[@]}
Array in FUNCTION Contains:
val1
Array in FUNCTION Contains:
val2
Array in FUNCTION Contains:
val3
1 Like

@Rudic thank you for the inputs. How can we assign the passed array to a variable in the function. I ask this becoz i did not get a chance to go back to my system and try out how to do that.

If your values will never contain spaces, you can "pass" arrays as strings "val1 val2 val3" and split them back inside the function, like this:

#!/bin/ksh

set -A filelist val1 val2 val3
set -A otherlist q1 q2 q3

verifyfiles() {
        set -A Flist $1
        set -A Qlist $2
        echo "flist[0]=${Flist[0]}"
        echo "qlist[0]=${Qlist[0]}"
}

verifyfiles "${filelist[*]}" "${otherlist[*]}"
2 Likes

Thank you .... Works Perfect @Corona @RudiC.

1 Like

Would name referencing be useful? This is Corona688's solution using namerefs:

#!/bin/ksh

set -A filelist val1 val2 val3
set -A otherlist q1 q2 q3

verifyfiles() {
   nameref Flist=$1
   nameref Qlist=$2
   echo "flist[0]=${Flist[0]}"
   echo "qlist[0]=${Qlist[0]}"
}

verifyfiles filelist otherlist

As you are passing by reference you can actually change the contents of the original array, which is probably a bad thing.

Andrew

Moderator comments were removed during original forum migration.