Redirection based on variables assigned within while loop setup

70 views Asked by At

I want to access while loop variable out side the loop

while read line
do
...
...
...
done < $file > /home/Logs/Sample_$line_$(date +"%Y%m%d_%H%M%S").log

In the above example whatever the log file is getting generated that doesn't have the value for the line variable. i.e. $line is not working here.

Please let me know how this can be written to make it work.

#!/bin/sh
exec 1> /home/Logs/`basename $0 | cut -d"." -f1 | sed 's/\.sh//g'`_$(date +"%Y%m%d_%H%M%S").log 2>&1
echo "Execution Started : `date` \n"
SQL_DIR=/home/Sql
INFILE=in_file
TEMPFILE=temp_file
RETURN_CODE=0
ls -ltr $SQL_DIR|grep ".sql"|awk -F" " '{print $9}'|awk -F"." '{print $1}' > $INFILE
sed '/^$/d' $INFILE > $TEMPFILE; mv $TEMPFILE $INFILE

while read line
do
      {
        START_TIME=`date +%s`

        printf "\n SQL File Executed Is : $line.sql"
        SQL_FILE_NM=$line.sql
        SQL_FILE=$SQL_DIR/$SQL_FILE_NM
        nzsql -db netezza_db -Atqf $SQL_FILE > /dev/null

        RETURN_CODE=$?
        if [ $RETURN_CODE -eq 0 ]; then
                echo "Time taken to execute sqlfile $SQL_FILE=$TT_HRS:$TT_MINS:$TT_REM_SECS HH:MM:SS" > $TEMPFILE
                printf "\n Success: Sql completed successfully at `date` \n"
                cat $TEMPFILE|mailx -s "Time taken to execute sqlfile $SQL_FILE=$TT_HRS:$TT_MINS:$TT_REM_SECS HH:MM:SS" '[email protected]'
        else
                printf "\n Error: Failed in sql execution at `date`"
                exit $RETURN_CODE
        fi

        END_TIME=`date +%s`
        TT_SECS=$(( END_TIME - START_TIME))
        TT_HRS=$(( TT_SECS / 3600 ))
        TT_REM_MS=$(( TT_SECS % 3600 ))
        TT_MINS=$(( TT_REM_MS / 60 ))
        TT_REM_SECS=$(( TT_REM_MS % 60 ))
        printf "\n"
        printf "Total time taken to execute the sql $line="$TT_HRS:$TT_MINS:$TT_REM_SECS HH:MM:SS
        printf "\n"
      } > /home/Logs/sql_query_time_$line_$(date +"%Y%m%d_%H%M%S").log

done < $INFILE

rm -f $INFILE $TEMPFILE
exit $RETURN_CODE
1

There are 1 answers

8
anubhava On BEST ANSWER

You actually need redirection inside the while loop:

while read -r line; do
   { cmd1; cmd2; cmd3; } > "/home/Logs/Sample_${line}_$(date +"%Y%m%d_%H%M%S").log"
done < "$file"

When you have > outfile after done then output is redirected to one file only.