Shell中的while循环【转】
2016-05-05 20:56
537 查看
转自:http://blog.chinaunix.net/uid-25880122-id-2901409.html
while循环的格式
while expression
do
command
command
```
done
1、计数器控制的while循环
主要用于已经准确知道要输入的数据和字符串的数目。
举例
1 #!/bin/sh
2 int=1
3 while(( $int<=5 ))
4 do
5 echo $int
6 let "int++"
7 done
2、结束标记控制的while循环
主要用于不知道读入数据的个数,但是可以设置一个特殊的数据值来结束循环,该特殊值称为结束标 记,通过提示用户输入进行操作。
举例
1 #用脚本演示使用结束标记控制while循环实现猜1~10内的数
2 #!/bin/sh
3
4 echo "Please input the num (1~~10): "
5 read num
6 while [[ $num != 4 ]]
7 do
8 if [ $num -lt 4 ]
9 then
10 echo "Too small ,Try again.."
11 read num
12 elif [ $num -gt 4 ]
13 then
14 echo "Too big ,Try again.. "
15 read num
16 else
17 exit 0
18 fi
19 done
20 echo "Yes ,you are right !!"
3、标致控制的while循环
用户输入标志值来控制循环结束
举例
1 #!/bin/sh
2 echo "Please input the num:"
3 read num
4 sum=0
5 i=1
6 signal=0
7 while [[ $signal != 1 ]]
8 do
9 if [ $i -eq $num ]
10 then
11 let "signal=1"
12 let "sum+=i"
13 echo "1+2、、、+$num=$sum"
14 else
15 let "sum=sum+i"
16 let "i++"
17 fi
18 done
4、命令行控制的while循环
举例
1 #!/bin/sh
2
3 echo "Please input arguements is $# "
4 echo "What you input : "
5 while [[ $* != "" ]]
6 do
7 echo $1
8 shift
9 done
while循环的格式
while expression
do
command
command
```
done
1、计数器控制的while循环
主要用于已经准确知道要输入的数据和字符串的数目。
举例
1 #!/bin/sh
2 int=1
3 while(( $int<=5 ))
4 do
5 echo $int
6 let "int++"
7 done
2、结束标记控制的while循环
主要用于不知道读入数据的个数,但是可以设置一个特殊的数据值来结束循环,该特殊值称为结束标 记,通过提示用户输入进行操作。
举例
1 #用脚本演示使用结束标记控制while循环实现猜1~10内的数
2 #!/bin/sh
3
4 echo "Please input the num (1~~10): "
5 read num
6 while [[ $num != 4 ]]
7 do
8 if [ $num -lt 4 ]
9 then
10 echo "Too small ,Try again.."
11 read num
12 elif [ $num -gt 4 ]
13 then
14 echo "Too big ,Try again.. "
15 read num
16 else
17 exit 0
18 fi
19 done
20 echo "Yes ,you are right !!"
3、标致控制的while循环
用户输入标志值来控制循环结束
举例
1 #!/bin/sh
2 echo "Please input the num:"
3 read num
4 sum=0
5 i=1
6 signal=0
7 while [[ $signal != 1 ]]
8 do
9 if [ $i -eq $num ]
10 then
11 let "signal=1"
12 let "sum+=i"
13 echo "1+2、、、+$num=$sum"
14 else
15 let "sum=sum+i"
16 let "i++"
17 fi
18 done
4、命令行控制的while循环
举例
1 #!/bin/sh
2
3 echo "Please input arguements is $# "
4 echo "What you input : "
5 while [[ $* != "" ]]
6 do
7 echo $1
8 shift
9 done
相关文章推荐
- LinuxShell_variable+if+while
- Win10系统开启Linux Bash命令行
- shell脚本自动化部署-如何向expect脚本里面传递参数
- 解决shell命令行只显示-bash-4.1#不显示用户和路径方法
- Shell中awk和sed的一些使用
- linux shell 数字计算详解
- 用PowerShell在China Azure创建ARM虚拟机
- shell 中的各种括号
- shell排序
- bash
- Linux中profile、bashrc、bash_profile之间的区别和联系
- Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
- linux shell 快捷键.
- shell 基础
- Mac 实用工具bash-comletion介绍安装
- 使用Xshell工具远程Linux环境部署web项目
- shell从入门到放弃(上)
- linux基础之bash特性
- Shell脚本总结
- Bash的基础特性