当前位置:网站首页>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 值的退出状态,从而导致判断条件不成立,结束循环。
边栏推荐
- Li Kou 1358 -- number of substrings containing all three characters (double pointer)
- 【无标题】
- Model and view of QT
- Brief introduction to AES
- What is 1cr0.5mo (H) material? 1cr0.5mo (H) tensile yield strength
- Insert mathematical formula in MD document and mathematical formula in typora
- Internet of things technology is widely used to promote intelligent water automation management
- MySQL8.0学习记录17 -Create Table
- Principle and application of single chip microcomputer - off chip development
- Programming with C language: calculate with formula: e ≈ 1+1/1+ 1/2! …+ 1/n!, Accuracy is 10-6
猜你喜欢

Nacos - 配置管理

Nacos - 服务发现

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

The era of low threshold programmers is gone forever behind the sharp increase in the number of school recruitment for Internet companies
![[JS reverse] MD5 encryption parameter cracking](/img/06/0610045d287f646479d6eb5021a067.png)
[JS reverse] MD5 encryption parameter cracking

Bimianhongfu queren()

SPL Introduction (I)

3. Detailed explanation of Modbus communication protocol

MATLAB小技巧(16)矩阵特征向量特征值求解一致性验证--层次分析
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
随机推荐
Advanced API
What is the material of 16MnDR, the minimum service temperature of 16MnDR, and the chemical composition of 16MnDR
MySQL8.0学习记录17 -Create Table
MATLAB小技巧(16)矩阵特征向量特征值求解一致性验证--层次分析
Matlab [functions and images]
DataBinding源码分析
《MATLAB 神经网络43个案例分析》:第30章 基于随机森林思想的组合分类器设计——乳腺癌诊断
[JS reverse] MD5 encryption parameter cracking
Programming with C language: calculate with formula: e ≈ 1+1/1+ 1/2! …+ 1/n!, Accuracy is 10-6
Nacos - 配置管理
如何解决固定资产管理和盘点的难题?
NIO-零拷贝
如何一站式高效管理固定资产?
factory type_ Id:: create process resolution
yolov5训练可视化指标的含义
Field agricultural irrigation system
ARM v7的体系结构A、R、M区别,分别应用在什么领域?
集团公司固定资产管理的痛点和解决方案
Share 7 books I read in the first half of 2022
Mavros sends a custom topic message to Px4