linux 中while循环
1、直接测试
[root@centos7pc1 test3]# ls test.sh [root@centos7pc1 test3]# cat test.sh ## 测试脚本 #!/bin/bash NUM=3 while [ $NUM -gt 0 ] ## 循环条件 do echo "xxxxx" let NUM-- ## 循环变量的控制 done [root@centos7pc1 test3]# bash test.sh xxxxx xxxxx xxxxx
2、改进
[root@centos7pc1 test3]# ls test.sh [root@centos7pc1 test3]# cat test.sh #!/bin/bash NUM=$1 ## 把循环次数设置为变量 while [ $NUM -gt 0 ] do echo "xxxxx" let NUM-- done [root@centos7pc1 test3]# bash test.sh 2 ## 自定义循环次数 xxxxx xxxxx [root@centos7pc1 test3]# bash test.sh 5 ## 自定义循环次数 xxxxx xxxxx xxxxx xxxxx xxxxx
3、其他用法
[root@centos7pc1 test3]# ls test.sh [root@centos7pc1 test3]# cat test.sh #!/bin/bash PRICE=$(expr $RANDOM % 1000) echo "the range of the price is 0~999!" TIMES=0 while true do read -p "please input your answer: " INT let TIMES++ if [ $INT -eq $PRICE ] then echo "yes, you are write!" echo "you had guessed $TIMES time!" echo "the price is $PRICE!" exit 0 elif [ $INT -gt $PRICE ] then echo "big, big!!!" else echo "small, small!!!" fi done [root@centos7pc1 test3]# bash test.sh the range of the price is 0~999! please input your answer: 500 small, small!!! please input your answer: 750 small, small!!! please input your answer: 850 big, big!!! please input your answer: 800 big, big!!! please input your answer: 775 small, small!!! please input your answer: 790 big, big!!! please input your answer: 780 big, big!!! please input your answer: 777 big, big!!! please input your answer: 776 yes, you are write! you had guessed 9 time! the price is 776!
分类:
linux shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律