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!

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。