Function call with argument doubt

Hi all,

I am having a problem with user defined function call. I am new into the concept of shell script UDFs.

My function is:

iterate_directory()
{
cd $1
k=0
for i in *
    do
        if [ -d "$i" ]
        then
            ARR[k++]=${i}
        fi
    done
echo ${ARR
[*]}
}

This is for iterate a directory and stored all sub-directories in an array

I called this function like this

directory="/tmp/"
array1=iterate_directory "$directory"

Please correct me, where I went wrong.

Hi,

You forgot to mention the shell you are using. Assigning a value to an array by calling a function does not work. Neither in bash or in ksh. As bash and ksh function variable scope is global by default, your array ARR is visible outside your function.

Oh, I am sorry.

I am using bash shell

GNU bash, version 3.2.48(1)-release (i486-pc-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.

if I drop that echo in my function is it going to work ?

No, as

is not correct. You can not assign a value to an array that way as the function only returns a code, not a value.
Just do something like this:

iterate_directory()
{
cd $1
k=0
for i in *
    do
        if [ -d "$i" ]
        then
            array1[k++]=${i}
        fi
    done
}

So there is no use of functions, if there is no means of re-usability then what is the need of functions ?:rolleyes: