曲径通幽论坛

标题: 控制循环语句: break 和 continue [打印本页]

作者: beyes    时间: 2009-1-2 21:24
标题: 控制循环语句: break 和 continue
break[n]
退出循环
如果是在一个嵌入循环里,可以指定 n 来跳出循环个数

continue
跳过循环步

:continue 命令类似于 break 命令,只有一点重要差别,它不会跳出循环,只是跳过这个循环步
作者: beyes    时间: 2009-1-2 21:34
标题: break 与 continue 应用举例
break 举例:
#!/bin/bash
#breakout
while :        # : 号为永远为真,且 : 和 while 之间要有空格
do
echo -n "Enter any number[1...5]:"
        read ANS
        case $ANS in
        1|2|3|4|5)
                echo "You enter a number between 1 and 5."
                ;;
        *)
                echo "Wrong number,bye.."
                break
                ;;
        esac
done

continue 应用举例:
#!/bin/bash
#breakout
while :
do
echo -n "Enter any number[1...5]:"
        read ANS
        case $ANS in
        1|2|3|4|5)
                echo "You enter a number between 1 and 5."
                ;;
        *)
                echo -n "Wrong number, continue(y/n)?:"
                read IS_CONTINUE
                case $IS_CONTINUE in
                        y|Y|yes|Yes)
                                continue
                                ;;
                        *)
                                break
                                ;;
                esac

        esac
done

作者: beyes    时间: 2009-1-21 16:29
标题: break 示例-2
#!/bin/bash

rm -rf fred*
echo > fred1
echo > fred2

mkdir fred3
echo > fred4

for file in fred*
do
        if [ -d "$file" ]; then
break;
        fi
done

echo first directory starting fred was $file

rm -rf fred*

exit 0

作者: beyes    时间: 2009-1-21 21:43
标题: 嵌套循环中用 continue
嵌套两个循环
#!/bin/bash

for x in 1 2 3 4 5 6 7 8
do
echo $x

        for y in a b c d e f g
        do
echo -n $y
        done

echo -e "\\n------------------"
done

输出结果
[beyes@localhost shell]$ sh for_test_4.sh
1
abcdefg
------------------
2
abcdefg
------------------
3
abcdefg
------------------
4
abcdefg
------------------
5
abcdefg
------------------
6
abcdefg
------------------
7
abcdefg
------------------
8
abcdefg
------------------

修改一下源码(添加一行 continue 2)
#!/bin/bash

for x in 1 2 3 4 5 6 7 8
do
echo $x

        for y in a b c d e f g
        do
               echo -n $y
                continue 2      # continue 后,数字1表示在本层循环;2表示上一层循环;以此类推...
        done

echo -e "\\n------------------"
done





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2