【问题标题】:How to exit/break from nested if-else statement once conditions are met满足条件后如何退出/中断嵌套的 if-else 语句
【发布时间】:2017-09-14 07:46:44
【问题描述】:

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

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

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

【问题讨论】:

    标签: shell if-statement exit break


    【解决方案1】:

    我发现更好的方法是使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多