一旦满足条件,如何从嵌套的if-else语句退出/中断

时间:2017-09-14 07:46:44

标签: shell if-statement exit break

我有一个脚本,它使用嵌套的if-else语句来搜索文件。我希望一旦满足任何一个嵌套语句的条件,脚本就会退出。

但是脚本仍然会继续运行所有剩余的if-else语句。

我已经使用exit 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

1 个答案:

答案 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