2017-09-14 24 views
0

我有一個使用嵌套的if-else語句來搜索文件的腳本。我希望腳本在任何一個嵌套語句符合條件時退出。如何在遇到條件時從嵌套的if-else語句中退出/斷開

但腳本仍然繼續運行所有其餘的if-else語句。

我已經測試過使用退出0並返回0,但都不起作用。

這裏的腳本:

#!/bin/sh 

PATH1=/filer1_vol1_dir1 
PATH2=/filer2_vol1_dir1 
PATH3=/filer3_vol1_dir2 
PATTERN=fruits 

find $PATH1 -type f -name "*$PATTERN*" -exec ls -l {} \; >> /tmp/${PATTERN}_search 

if [[ -s /tmp/${PATTERN}_search && `grep -i apples /tmp/${PATTERN}_search` ]] 
then 
     echo "Matching files have been found under $PATH1" 
     cat /tmp/${PATTERN}_search 
     return 0 
else 
     echo "No matching files, proceeding to search $PATH2" 
     find $PATH2 -type f -name "*$PATTERN*" -exec ls -l {} \; >> /tmp/${PATTERN}_search 

     if [[ -s /tmp/${PATTERN}_search && `grep -i apples /tmp/${PATTERN}_search` ]] 
     then 
       echo "Matching files have been found under $PATH2" 
       cat /tmp/${PATTERN}_search 
       return 0 
     else 
       echo "No matching files, proceeding to search $PATH3" 
       find $PATH3 -type f -name "*$PATTERN*" -exec ls -l {} \; >> /tmp/${PATTERN}_search 

       if [[ -s /tmp/${PATTERN}_search && `grep -i apples /tmp/${PATTERN}_search` ]] 
       then 
         echo "Matching files have been found under $PATH3" 
         cat /tmp/${PATTERN}_search 
         return 0 
       else 
         echo "No file matches, please search elsewhere" 
         return 0 
       fi 
     fi 
fi 

exit 0 

回答

0

我發現,更好的方法是使用while循環通過每個搜索迭代。在每次迭代中,if-else條件將測試是否找到與查找模式匹配的文件。一旦這個條件成立,break語句就可以停止腳本。

以下示例腳本:

#!/bin/sh 

PATH1=/filer1_vol1_dir1 
PATH2=/filer2_vol1_dir1 
PATH3=/filer3_vol1_dir2 
PATTERN=fruits 

echo $PATH1 > /tmp/PATH.list 
echo $PATH2 >> /tmp/PATH.list 
echo $PATH3 >> /tmp/PATH.list 
echo /tmp/PATH.list contains 
cat /tmp/PATH.list 
echo 

cat /dev/null > /tmp/${PATTERN}_search.list 

while read PATH 
do 

echo "Searching under the following parameters" 
echo PATTERN = $PATTERN 
echo PATH = $PATH 
echo 
/usr/bin/find $PATH -type f -name "*$PATTERN*" -exec ls -l {} \; >> /tmp/${PATTERN}_search.list 

/usr/bin/grep -i apples /tmp/${PATTERN}_search.list 
if [ $? -eq 0 ] 
then 
    echo "All matching files have been found." 
    break 
else 
    echo "No matches found, continuing search in next directory." 
fi 

done < /tmp/PATH.list 

exit 0