Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Returning the value of a variable within a loop 2

Status
Not open for further replies.

edwardb001

Technical User
Sep 14, 2003
2
AU
Hi,
how can i return the value of a variable used within a loop to the main program?
from the below example, the value of $loop_counter is different once the program exits the while loop (within the while loop, $loop_counter is the value of the number of times records a read, but once exiting the loop, $loop_counter is 1)
thanks.

#! /bin/sh
loop_counter=1; export loop_counter
while read FX_Cash_Flow_Report_details
do

cp $FX_Cash_Flow_Report_details ${new_report_name}_${loop_counter}_rpt
loop_counter=`expr $loop_counter + 1`; export loop_counter
echo $loop_counter
done < $INFINITY_REPORTS_LOG_DIR/${new_report_name}.fnd
echo $loop_counter
 
Try something like this:
Code:
#! /bin/sh
loop_counter=1; export loop_counter
exec < $INFINITY_REPORTS_LOG_DIR/$new_report_name.fnd
while read FX_Cash_Flow_Report_details; do
  cp $FX_Cash_Flow_Report_details ${new_report_name}_${loop_counter}_rpt 
  loop_counter=`expr $loop_counter + 1`
  echo $loop_counter
done
echo $loop_counter
So the read loop is not executed in a subshell.

Hope This Help
PH.
 
Note: with the above logic, the final value of $loop_counter will be equal to the number of records read plus one. To avoid this, set it zero initially and increment before the copy, like......

#! /bin/sh
loop_counter=0; export loop_counter
for FX_Cash_Flow_Report_details in `cat $INFINITY_REPORTS_LOG_DIR/${new_report_name}.fnd`
do
loop_counter=`expr $loop_counter + 1`; export loop_counter
cp $FX_Cash_Flow_Report_details ${new_report_name}_${loop_counter}_rpt
echo $loop_counter
done
echo $loop_counter
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top