当前位置:网站首页>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 值的退出状态,从而导致判断条件不成立,结束循环。
边栏推荐
- IT 技术电子书 收藏
- Pipeline detection of UAV Based on gazebo
- Nacos - service discovery
- 嵌入式工程师面试题3-硬件
- V79.01 Hongmeng kernel source code analysis (user mode locking) | how to use the fast lock futex (Part 1) | hundreds of blogs analyze the openharmony source code
- win7 pyinstaller打包exe 后报错 DLL load failed while importing _socket:参数错误
- Model and view of QT
- 集团公司固定资产管理的痛点和解决方案
- Shell脚本-位置参数(命令行参数)
- Guidelines and principles of did
猜你喜欢
What is the material of 16mo3 steel plate? What is the difference between 16mo3 and Q345R?
你了解数据是如何存储的吗?(C整型和浮点型两类)
集团公司固定资产管理的痛点和解决方案
Public network cluster intercom +gps visual tracking | help the logistics industry with intelligent management and scheduling
Nacos - service discovery
Computer tips
Matlab [function derivation]
19Mn6 German standard pressure vessel steel plate 19Mn6 Wugang fixed binding 19Mn6 chemical composition
Matlab tips (23) matrix analysis -- simulated annealing
基础:2.图像的本质
随机推荐
Shell脚本-for循环和for int循环
2022.2.15
Agrometeorological environment monitoring system
Vscode customize the color of each area
Review of week 280 of leetcode
公网集群对讲+GPS可视追踪|助力物流行业智能化管理调度
The use of word in graduation thesis
VSYNC+三重缓存机制+Choreographer
为什么LTD独立站就是Web3.0网站!
In depth learning training sample amplification and tag name modification
AVL树的理解和实现
深度学习训练样本扩增同时修改标签名称
What is 1cr0.5mo (H) material? 1cr0.5mo (H) tensile yield strength
C语言指针的进阶(下)
Principle and application of single chip microcomputer - off chip development
FreeRTOS学习简易笔记
又到年中,固定资产管理该何去何从?
截图小妙招
[Yu Yue education] Shandong Vocational College talking about railway reference materials
Nacos - service discovery