[ksh93+] Array fed by function is empty when used in main.

I feel that i am missing something obvious but i can't find what is wrong.

I have a script that is launching some functions with "&" and each call is feeding the array with a value. When all calls are finished I just want to retrieve the values of that array.

It is looking like that :

#!/user/bin/ksh

#Function called with & 
fct()
{
 sleep $1
 tab_track[$1]="$(date)"
}

#Main
for OneIteration in 1 2 3 4 5
do
fct $OneIteration &
done

wait

echo "Display time"

for OneLine in "${tab_track[@]}"
do
   echo ${OneLine}
done

Any idea ?

Hi,

fct $OneIteration &

will get executed in a subshell in the background, so any assigned values will be lost, once it finishes..

If you wanted to do multiple commands at once and save their results in order, you must first save them separately, because once they're in the background they'll run in no particular order at all.

#Function called with & 
fct()
{
 sleep $1
 date
}

for X in 1 2 3 4 5
do
        fct > /tmp/$$-$X &
done

wait # Let them all finish

# Set the array
set -a ARR `cat /tmp/$$-*`

# Remove temp files
rm -f /tmp/$$-*

I am not trying to get the results in particular order but I need to retrieve all of them :slight_smile: I was not considering the use temporary file but it seems the way to go. Thanks for pointing me to the right directions.

Considering that they might return results inside each others with no respect for things like linebreaks, one big pile is not the way to go.

Yes, each bg proc needs its own output file or pipe, unless you can ensure they write() blocks of whole lines. I had to clean up some shared logs in C/C++, using setvbuf() to make the log's FILE* buffer big, and fflush() to ship each buffered message in a single write(). In shell, you might have problems ensuring atomic line write(). If you want sorted outputsort can be a buffer:

sort -m <( script_1 | sort ) <( script_2 | sort ) <( script_3 | sort ) <( script_4 | sort ) <( script_5 | sort ) >output_file