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!