Unix循环if条件和退出命令

时间:2014-11-20 13:15:31

标签: unix

我遇到一个问题,我必须从Path.lst中给出的某些文件夹中删除文件, 整个脚本工作正常但是当在Path.lst中给出一些错误的路径时,脚本会退出循环并且不对下一个路径执行任何操作。

但最后一行

echo -e "\n ENDING SCRIPT SUCCESSFULLY ON `date` " >> $LOG_FILE

执行,因为退出1在此部分不起作用

if [ ! -d $path ]       
then
echo -e "\nERROR :$path IS INVALID." >> $LOG_FILE

echo -e "\nENDING SCRIPT WITH ERRORS ON `date`" >> $LOG_FILE
exit 1

---------------------------------------------------------------------------------------
THE SCRIPT IS LIKE :

echo -e "\nSTARTING SCRIPT ON `date`">> $LOG_FILE

if  [ $1 -gt 0 ]
then
DAYS_BFOR="$1"
else
echo -e "\nERROR :Please pass a single positive integer to the script" >>$LOG_FILE
echo -e "\nENDING SCRIPT WITH ERRORS ON `date` " >> $LOG_FILE

exit
fi

cat Path.lis | sed 's|^PATH[0-9]*=||g' |  while read path
do
if [ ! -d $path ]
then
echo -e "\nERROR :$path IS INVALID." >> $LOG_FILE
echo -e "\n ENDING SCRIPT WITH ERRORS ON `date` " >> $LOG_FILE

exit 1
else
echo -e "\nFILES DELETED FROM THE "$path" DIRECTORY --" >> $LOG_FILE

find $path -type f -mtime +$DAYS_BFOR  -printf "%TY-%Tm-%Td %kKB %p\n" | column -t | sed "s|"$path"||g" >> $LOG_FILE 2>&1

file_count=`find $path -type f -mtime +$DAYS_BFOR | wc -l`

if [ $file_count -ge 1 ]
then
find $path -type f -mtime +$DAYS_BFOR  | xargs rm 2>>$LOG_FILE 2>&1
fi
fi

done

echo Exit Status : $?
echo -e "\n ENDING SCRIPT SUCCESSFULLY ON `date`" >> $LOG_FILE

请帮助并解释原因。

1 个答案:

答案 0 :(得分:0)

如果你只想要" ENDING SCRIPT SUCCESSFULLY"如果文件被成功删除则显示消息,如果给出了无效路径,则可以将最后两个回显行移动到else语句的末尾,如下所示:

 else
            echo -e "\nFILES DELETED FROM THE "$path" DIRECTORY --" >> $LOG_FILE
            find $path -type f -mtime +$DAYS_BFOR  -printf "%TY-%Tm-%Td %kKB %p\n" | column -t | sed "s|"$path"||g" >> $LOG_FILE 2>&1
            file_count=`find $path -type f -mtime +$DAYS_BFOR | wc -l`

            if [ $file_count -ge 1 ]
            then
                    find $path -type f -mtime +$DAYS_BFOR  | xargs rm 2>>$LOG_FILE 2>&1
            fi

            echo Exit Status : $?
            echo -e "\n--------------------------- ENDING SCRIPT SUCCESSFULLY ON `date` ----------------------------------" >> $LOG_FILE

    fi

done

如果您只想跳到Path.lis文件中的下一个项目,那么只需从第一个循环中删除exit语句。这样它将继续执行脚本,直到文件中的所有行都被读取,如果当前文件不是有效路径,则只显示错误。