当前位置:网站首页>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 值的退出状态,从而导致判断条件不成立,结束循环。
边栏推荐
- What is the material of 16MnDR, the minimum service temperature of 16MnDR, and the chemical composition of 16MnDR
- 我想知道手机注册股票开户的流程?另外,手机开户安全么?
- 又到年中,固定资产管理该何去何从?
- 《微机原理》-绪论
- Foundation: 3 Opencv getting started images and videos
- 一文纵览主流 NFT 市场平台版税、服务费设计
- 【C】 Summary of wrong questions in winter vacation
- 【无标题】
- 避免按钮重复点击的小工具bimianchongfu.queren()
- SPL installation and basic use (II)
猜你喜欢

15Mo3 German standard steel plate 15Mo3 chemical composition 15Mo3 mechanical property analysis of Wuyang Steel Works

MATLAB【函数求导】

【C】 Summary of wrong questions in winter vacation

Advanced level of C language pointer (Part 1)

Model and view of QT

Audio audiorecord create (I)

嵌入式工程师面试题3-硬件

如何一站式高效管理固定资产?

DID的使用指南,原理

Nacos - 配置管理
随机推荐
DataBinding源码分析
[deep analysis of C language] - data storage in memory
Matlab tips (23) matrix analysis -- simulated annealing
MATLAB小技巧(16)矩阵特征向量特征值求解一致性验证--层次分析
5mo3 UHI HII HII 17mn4 19Mn6 executive standard
Memory size end
爬虫知识点总结
大型工厂设备管理痛点和解决方案
Pipeline detection of UAV Based on gazebo
Nacos - 服务发现
Public network cluster intercom +gps visual tracking | help the logistics industry with intelligent management and scheduling
How to recruit Taobao anchor suitable for your own store
Intelligent water conservancy solution
R语言观察日志(part24)--初始化设置
3、Modbus通讯协议详解
2022.2.15
明明设计的是高带宽,差点加工成开路?
Bimianhongfu queren()
Matlab [functions and images]
NIO-零拷贝