在bash编程中,经常会涉及使用while语句,时常处理未知循环次数的情况。
- while语法
while [ express ] do #command Done
2. 实战练习
- 提示输入大于10小于20的整数;
while1.sh: #!/bin/bash echo -n "please input a digit between 10 and 20:" read n while [ $n -lt 10 ]||[ $n -gt 20 ] do echo -n "please input a digit between 10 and 20:" read n done echo "your digit is $n,thank you!"
- 猜数字,猜中则结束;
while2.sh: #!/bin/bash echo -n "please guess a number between 0 and 10:" read n while [ $n -ne 8 ] do echo -n "please guess again(0-10):" read n done echo "congratulation,you guessed! the lucky number is 8!"
- 通过执行脚本时带入的参数控制while
while3.sh: #!/bin/bash n=$1 while [ -n "$n"] [ "$n" -gt 0 ] do echo -n "*" let n-- done ------------------------- $bash while3.sh 5 $*****
- 关于break和continue的使用。关键字"break" 用来跳出循环,而关键字”continue”用来不执行余下的部分而直接跳到下一个循环。
while4.sh: #!/bin/bash n=$1 while [ -n $n] do if [ $n -eq 0] then echo -e "" break else echo -n "*" let n-- continue fi done 执行:$bash while4.sh 5 *****
时间: 2024-12-30 03:52:04