Background tasks in a loop (bash)

I am trying to use a loop to start tasks 0-3, running 0,1,2 in the background with &.

FOLDSET=( 0 1 2 3 )

for FOLDSET in ${FOLDSET[@]}
do
   if [ $FOLDSET -lt 3 ]; then
     BACKGRD="&"
   else
     BACKGRD=""
   fi
   # start task $FOLDSET
   task1 -nogui -ni -p $PROJ \
      epochs=$EPOS  batches=$BATCH  n_threads=$THRD \
      arch=$ARCH  data_set=$DSET  fldTag=f$FOLDSET  $BACKGRD
done

I am truing to append & to the first three task (0,1,2), but not have & after the 4th. This will pause the script after task 4 and wait for it to finish before moving on. This is not working. I have tried & with and without the quotes with no difference. The code starts a four tasks, but in sequence instead of simultaneously.

Any suggestions, or am I going about this all wrong.

LMHmedchem

task1 -nogui -ni -p $PROJ \
      epochs=$EPOS  batches=$BATCH  n_threads=$THRD \
      arch=$ARCH  data_set=$DSET  fldTag=f$FOLDSET  $BACKGRD &

$BACKGRD has the value of "&" for the first three time through the loop, but apparently that doesn't work.

I can probably do this like ,

FOLDSET=( 0 1 2 3 )

for FOLDSET in ${FOLDSET[@]}
do
   if [ $FOLDSET -lt 3 ]; then
      # start the first three in the background
      task1 -nogui -ni -p $PROJ \
         epochs=$EPOS  batches=$BATCH  n_threads=$THRD \
         arch=$ARCH  data_set=$DSET  fldTag=f$FOLDSET &
   else
      # wait on the last one
      task1 -nogui -ni -p $PROJ \
          epochs=$EPOS  batches=$BATCH  n_threads=$THRD \
          arch=$ARCH  data_set=$DSET  fldTag=f$FOLDSET
   fi
done

unless there are other/better suggestions.

LMHmedchem

Remove $BACKGROUND and put a real & there, then.

Put them all in the background, then use the wait builtin to wait for all your background processes to finish.