linux中while循环语句
1、测试1 求1-100的和
[root@centos7 test2]# cat test.sh
#!/bin/bash
sum=0
a=1
while [ $a -le 100 ]
do
let sum+=$a
let a++
done
echo "the sum of 1-100 is: $sum"
[root@centos7 test2]# bash test.sh
the sum of 1-100 is: 5050
2、用户输入决定程序循环的次数
[root@centos7 test2]# cat test.sh
#!/bin/bash
read -p "please input your choise: " choise
while [ $choise != q ]
do
read -p "input an number: " number
tmp=$(expr $number % 2)
if [ $tmp -eq 0 ]
then
echo "even!"
else
echo "odd"
fi
echo "choose to continue or quit. q: quit; other:continue!"
read -p "please input your choise: " choise
done
[root@centos7 test2]# bash test.sh
please input your choise: e
input an number: 8
even!
choose to continue or quit. q: quit; other:continue!
please input your choise: y
input an number: 7
odd
choose to continue or quit. q: quit; other:continue!
please input your choise: q
3、编写程序 每隔10秒显示系统负载、内存信息
[root@centos7 test2]# cat test.sh
#!/bin/bash
while true
do
uptime
free -h
echo "____________________________________________________________________________________________________"
sleep 10
done
4、结合read语句逐行读取数据
[root@centos7 test2]# cat test.sh
#!/bin/bash
seq 50 | while read i
do
tmp=$(expr $i % 5)
if [ $tmp -eq 0 ]
then
echo "$i"
fi
done
[root@centos7 test2]# bash test.sh
5
10
15
20
25
30
35
40
45
50
继续
[root@centos7 test2]# cat a.txt
4 8
2 5
1 4
6 3
3 2
[root@centos7 test2]# cat test.sh
#!/bin/bash
cat a.txt|while read i
do
a=$(echo $i | cut -d " " -f 1)
b=$(echo $i | cut -d " " -f 2)
c=$(expr $a \* $b)
echo "$c"
done
[root@centos7 test2]# bash test.sh
32
10
4
18
6
分类:
linux shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律