当前位置:网站首页>Shell脚本-while循环详解
Shell脚本-while循环详解
2022-07-01 08:36:00 【小蜗牛的路】
while 循环是 Shell 脚本中最简单的一种循环,当条件满足时,while 重复地执行一组语句,当条件不满足时,就退出 while 循环。
用法如下:
while condition
do
statements
done
condition表示判断条件,statements表示要执行的语句(可以只有一条,也可以有多条),do和done都是 Shell 中的关键字。
代码1:计算从 1 加到 100 的和。
#!/bin/bash
i=1
sum=0
while ((i <= 100))
do
((sum += i))
((i++))
done
echo "The sum is: $sum"
输出:
The sum is: 5050
在 while 循环中,只要判断条件成立,循环就会执行。对于这段代码,只要变量 i 的值小于等于 100,循环就会继续。每次循环给变量 sum 加上变量 i 的值,然后再给变量 i 加 1,直到变量 i 的值大于 100,循环才会停止。
i++语句使得 i 的值逐步增大,让判断条件越来越趋近于“不成立”,最终退出循环。
代码2:计算从 m 加到 n 的值。
#!/bin/bash
read m
read n
sum=0
while ((m <= n))
do
((sum += m))
((m++))
done
echo "The sum is: $sum"
输出:
1
100
The sum is: 5050
代码3:实现一个简单的加法计算器,用户每行输入一个数字,计算所有数字的和。
#!/bin/bash
sum=0
echo "请输入您要计算的数字,按 Ctrl+D 组合键结束读取"
while read n
do
((sum += n))
done
echo "The sum is: $sum"
输出:
请输入您要计算的数字,按 Ctrl+D 组合键结束读取
333
444
111
The sum is: 888
Ctrl+D组合键:在终端中读取数据,可以等价为在文件中读取数据,按下 Ctrl+D 组合键表示读取到文件流的末尾,此时 read 就会读取失败,得到一个非 0 值的退出状态,从而导致判断条件不成立,结束循环。
边栏推荐
- Matlab tips (23) matrix analysis -- simulated annealing
- What is the material of 15CrMoR, mechanical properties and chemical analysis of 15CrMoR
- Intelligent constant pressure irrigation system
- Intelligent water conservancy solution
- Shell脚本-select in循环
- Redis源码学习(29),压缩列表学习,ziplist.c(二)
- Yolov3, 4, 5 and 6 Summary of target detection
- MATLAB【函数和图像】
- Pipeline detection of UAV Based on gazebo
- 機動目標跟踪——當前統計模型(CS模型)擴展卡爾曼濾波/無迹卡爾曼濾波 matlab實現
猜你喜欢
![Matlab [function derivation]](/img/ba/9fb9da8a458d0c74b29b21a17328fc.png)
Matlab [function derivation]

Mavros sends a custom topic message to Px4

内存大小端

Do you know how data is stored? (C integer and floating point)

What is the material of 16MnDR, the minimum service temperature of 16MnDR, and the chemical composition of 16MnDR

Matlab tips (23) matrix analysis -- simulated annealing

基于Gazebo的无人机管道检测

How can enterprises and developers take the lead in the outbreak of cloud native landing?

Audio audiorecord create (I)

VSYNC+三重缓存机制+Choreographer
随机推荐
3、Modbus通讯协议详解
Glitch free clock switching technology
目标检测的yolov3、4、5、6总结
我想知道手机注册股票开户的流程?另外,手机开户安全么?
嵌入式工程师常见面试题2-MCU_STM32
截图小妙招
【MFC开发(17)】高级列表控件List Control
There are many problems in sewage treatment, and the automatic control system of pump station is solved in this way
内存大小端
Li Kou 1358 -- number of substrings containing all three characters (double pointer)
Agrometeorological environment monitoring system
【面试必刷101】链表
The era of low threshold programmers is gone forever behind the sharp increase in the number of school recruitment for Internet companies
一文纵览主流 NFT 市场平台版税、服务费设计
What is the material of 16MnDR, the minimum service temperature of 16MnDR, and the chemical composition of 16MnDR
Nacos - Configuration Management
任务、线程、进程 区别
In depth learning training sample amplification and tag name modification
Glitch Free时钟切换技术
爬虫知识点总结