break 语句

break 语句允许我们退出当前循环。
它通常用于包含在 while 循环中的 if 语句,while 循环中的条件总是评估为真。
如果循环执行的次数取决于用户的输入而不是某个预定的次数,这将很有用。

break 语句退出包含它的最内层循环。

$ cat break.ksh 
#!/bin/ksh
# Script name: break.ksh
typeset -i  num=0
while true
 do
     print -n "Enter any number (0 to exit): "
   read num junk

    if (( num == 0 ))
        then 
    break
        else 
    print "Square of $num is $(( num * num )). \n"
        fi 
done
print "script has ended"
$ ./break.ksh 
Enter any number (0 to exit): 5 
Square of 5 is 25.
Enter any number (0 to exit): -5 
Square of -5 is 25.
Enter any number (0 to exit): 259 
Square of 259 is 67081.
Enter any number (0 to exit): 0 
script has ended

使用 continue 语句的示例

以下 continue.ksh 示例脚本将当前目录中名称包含大写字母的文件重命名为小写字母。
首先,脚本打印当前正在处理的文件的名称。
如果此文件名不包含大写字母,则脚本执行 continue 语句,强制 shell 转到 for 循环的开头并获取下一个文件名

如果文件名包含大写字母,则原始名称保存在 orig 变量中。
名称也被复制到新变量中;但是,脚本开头的 typeset -l new 行会导致变量中存储的所有字母在赋值期间都转换为小写。
完成后,脚本使用 orig 和 new 变量作为参数执行 mv 命令。

然后,脚本会打印一条有关文件名称更改的消息,并获取要处理的下一个文件。
当 for 循环完成时,会打印 Done 消息,让用户知道脚本已完成。

$ cat continue.ksh
#!/bin/ksh
# Script name: continue.ksh
typeset -l new # Changes the variable’s contents  
# to lowercase characters
for file in *
do
    print "Working on file $file..."

    if [[ $file != *[A-Z]* ]]
    then 
        continue
    fi

    orig=$file
    new=$file
    mv $orig $new 
    print "New file name for $orig is $new."
done
print "Done."
$ cd test.dir
$ ls
Als             a               sOrt.dAtA       slAlk 
Data.File       recreate_names  scR1            teXtfile
$ ../continue.ksh 
Working on file Als... 
New file name for Als is als. 
Working on file Data.File... 
New file name for Data.File is data.file. 
Working on file a... 
Working on file recreate_names... 
Working on file sOrt.dAtA... 
New file name for sOrt.dAtA is sort.data. Working on file scR1... 
New file name for scR1 is scr1. Working on file slAlk... 
New file name for slAlk is slalk. Working on file teXtfile... 
New file name for teXtfile is textfile. 
Done.
$ ls 
a               data.file       scr1            sort.data 
als             recreate_names  slalk           textfile

注意:在执行 mv 命令之前,脚本不会检查文件名的大小写。

https://onitroad.com 更多教程

continue 语句

在循环中使用 continue 语句可以强制 shell 跳过循环中出现在 continue 语句下方的语句,并返回到循环顶部进行下一次迭代。
当我们在 for 循环中使用 continue 语句时,变量 var 采用列表中下一个元素的值。
当我们在 while 或者 until 循环中使用 continue 语句时,执行将通过循环顶部的 control_command 测试恢复执行。

如何在 shell 脚本中使用“break”和“continue”语句
日期:2020-09-17 00:14:55 来源:oir作者:oir