calling a shell script in background and wait using "wait" in while loop

Hi,
I am facing a strange issue,
when i call a script from my while loop in background it doesnt go in background, despite the wait i put below the whil loop it goes forward even before the process put in background is completed.

cat abc.txt | while read -u4 line
do
   #if line contains # dont proces that line and continue to next line
   echo $line | grep '#' > /dev/null
   if [[ $? -eq 0 ]]; then
        echo ...skipping comment
        continue
   fi
   # extracting the values from cfg file
   username=`echo $line | cut -d" " -f1`
   hostname=`echo $line | cut -d" " -f2`
   dir=`echo $line | cut -d" " -f3`
   type=`echo $line | cut -d" " -f4`
   dmnname=`echo $line | cut -d" " -f5`
   mnserver=`echo $line | cut -d" " -f6`
   . ${TOOL_DIR}/formatReport.sh $hostname $dmnname $mnserver $curhour $type $reportdir $dir $curdate &
   echo "Process ID = $!"
done
wait
#further processing

file contents for abc.txt

abc  sun1  /prod/var/1  web1    web_43_1   mt_027_9043_1
def  sun2  /prod/var/2  web2    web_43_2   mt_027_9043_2
pqr  sun3  /prod/var/3  web3    web_43_3   mt_027_9043_3
 

---------- Post updated at 06:23 PM ---------- Previous update was at 06:14 PM ----------

Any help will be appreciated.. Guys any pointers to what can be issue?

It is probably because the while loop is executed in a subshell (right side of the pipe). Try using:

while read -u4 line
..
done < abc.txt
wait
#further processing
1 Like

If you use &, it will not wait for that process to complete i.e. it puts it in background and continue with its execution.
I am assuming that you want to wait till the processing is complete and then continue. If so, remove the & and try.

HTH
--ahamed