当前位置:网站首页>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 值的退出状态,从而导致判断条件不成立,结束循环。
边栏推荐
- Intelligent constant pressure irrigation system
- Properties of 15MnNiNbDR low temperature vessel steel, Wugang 15MnNiDR and 15MnNiNbDR steel plates
- The meaning of yolov5 training visualization index
- Principle and application of single chip microcomputer - principle of parallel IO port
- 嵌入式工程师面试题3-硬件
- IT 技术电子书 收藏
- 1.jetson与摄像头的对接
- Matlab [function derivation]
- Nacos - 配置管理
- MD文档中插入数学公式,Typora中插入数学公式
猜你喜欢

Audio-AudioRecord create(一)

Intelligent water and fertilizer integrated control system

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

Memory size end

你了解数据是如何存储的吗?(C整型和浮点型两类)

内存大小端

C语言指针的进阶(上篇)

Maneuvering target tracking -- current statistical model (CS model) extended Kalman filter / unscented Kalman filter matlab implementation

【无标题】

Screenshot tips
随机推荐
毕业论文中word的使用1-代码域标公式
MD文档中插入数学公式,Typora中插入数学公式
VSYNC+三重缓存机制+Choreographer
[MFC development (17)] advanced list control list control
Advanced API
What is 1cr0.5mo (H) material? 1cr0.5mo (H) tensile yield strength
固定资产管理系统让企业动态掌握资产情况
1. Connection between Jetson and camera
基础:2.图像的本质
Share 7 books I read in the first half of 2022
TypeError: __init__() got an unexpected keyword argument ‘autocompletion‘
Redis源码学习(29),压缩列表学习,ziplist.c(二)
又到年中,固定资产管理该何去何从?
如何做好固定资产管理?易点易动提供智能化方案
AVL树的理解和实现
中考体育项目满分标准(深圳、安徽、湖北)
【无标题】
《单片机原理及应用》—定时器、串行通信和中断系统
Principle and application of single chip microcomputer - principle of parallel IO port
win7 pyinstaller打包exe 后报错 DLL load failed while importing _socket:参数错误