基于 while 循环设置中分配的变量的重定向

Redirection based on variables assigned within while loop setup

我想在循环外访问 while 循环变量

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

在上面的示例中,无论生成什么日志文件,它都没有 line 变量的值。即 $line 在这里不起作用。

请告诉我如何编写才能使其工作。

#!/bin/sh
exec 1> /home/Logs/`basename [=11=] | 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 }'|awk -F"." '{print }' > $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" 'koushik.chandra@a.com'
        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

您实际上需要在 while 循环内进行重定向:

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

done 之后有 > outfile 时,输出将仅重定向到一个文件。