Directory sizes loop optimization

I have the following script:

#!/usr/bin/ksh

export MDIR=/datafiles

NAME=$1
SERVER=$2
DIRECTORY=$3
DATABASE=$4
ID=$5

export dirlist=`/usr/bin/ssh -q $ID@$SERVER find $DIRECTORY -type d -print`
for dir in $dirlist
do
SIZE=`</dev/null /usr/bin/ssh -q $ID@$SERVER du -ks $dir`
echo $NAME $DATABASE $SIZE $DIRECTORY>> $MDIR/bldtuout.txt
done

It is running forever, but does return the correct results. Is there a faster way? My goal is to have the directory sizes of all directories under a given path.

Why use the for-loop when it can all be done by find.

/usr/bin/ssh -q $ID@$SERVER find $DIRECTORY -type d -exec du -sk {} \;

So, it should look like this:

#!/usr/bin/ksh

export MDIR=/datafiles

NAME=$1
SERVER=$2
DIRECTORY=$3
DATABASE=$4
ID=$5

SIZE=`/usr/bin/ssh -q $ID@$SERVER find $DIRECTORY -type d -exec du -sk {} \;`
echo $NAME $DATABASE $SIZE $DIRECTORY>> $MDIR/bldtuout.txt
done

When I try to run it, I get find: incomplete statement What am I doing wrong?

You probably need to double (or triple or quadruple) the backslash in order for the remote ssh to receive it correctly.

Put it in double-quotes and use $(cmd) instead of `cmd` which makes it much easier to follow.

SIZE=$(/usr/bin/ssh -q $ID@$SERVER "find $DIRECTORY -type d -exec du -sk {} \;")

Thank you! That did it.

Two more questions:
Now the output is all on one line, is there a quick way to parse it to multiple lines?

When the find creates an error, it is written to the screen, is there a way to get it writen to an output file?

I figured it out. My script now looks like:

Thank yiou to everyone for your help.