shell补-循环案例-当型循环while和直到型循环do until
shell补-循环案例-当型循环while和直到型循环do until
循环分类:
类型 | 含义 | 应用场景 |
---|---|---|
while循环 | 当型循环(当满足或不满足) | 死循环 循环读取文件或管道内容 |
do until 循环 | 直到型循环(一直进行循环直到不满足条件) | 很少使用 |
for 循环 | 通用 |
while循环应用场景:
- 死循环/有条件循环
- 脚本while读取文件内容(文件里面ip/url)
- while语法
while <条件表达式>
do
命令1
done
#####################
while <条件表达式>;do
命令1
done
###################
###死循环
while true #这个条件永久成立,或者写成:也行
do
命令1
sleep 1 ###可以加上,防止刷屏太快
done
######################################给颜色变化脚本加上循环,重新录入
[root@localhost color]# cat testcolorwhil.sh
#!/bin/bash
red="\e[1;31m"
green="\e[1;32m"
end="\e[0m"
login()
{
cat << EOFS
1.input [red|r] and your content set red foreground!
2.input [green|g] and your content set green foreground!
3.input [exits] and your exit!
EOFS ######注意这个结尾符要顶格写才有效
}
input(){
read colors content
case "${colors}" in
"red"|"r")
echo -e "${red}${content}${end}"
;;
"green"|"g")
echo -e "${green}${content}${end}"
;;
"exits")
echo "程序将退出" ######加上退出功能
sleep 3
exit
;;
*)
echo "you must inpuut {red|r|green|g}"
continue
;;
esac
}
main(){
login
while true
do
input
sleep 2
done
}
main
[root@localhost color]#
[root@localhost color]# bash testcolorwhil.sh
1.input [red|r] and your content set red foreground!
2.input [green|g] and your content set green foreground!
r hell
hell
r hllo
hllo
g hell
hell
[root@localhost color]# bash testcolorwhil.sh
1.input [red|r] and your content set red foreground!
2.input [green|g] and your content set green foreground!
3.input [exits] and your exit!
red hello
hello
greep back
you must inpuut {red|r|green|g}
exit
you must inpuut {red|r|green|g}
green back
back
exits
程序将退出
[root@localhost color]#
-
until 直到
until 状态没钱 do 消费 done
注意:这个地方还没搞懂,空了看
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!