Shell中的while循环几种使用实例详解
技术  /  管理员 发布于 7年前   130
1.利用while循环计算1到100的和:
示例代码1:
#!/bin/bashi=1sum=0while [ $i -le 100 ]do let sum=sum+$i let i++doneecho $sum
示例代码2:利用while循环计算1到100之间所有奇数之和
#!/bin/bashi=1sum=0while [ $i -le 100 ]do let sum=sum+$i let i+=2doneecho $sum
示例代码3:利用while循环计算1到100之间所有偶数之和
#!/bin/bashi=2sum=0while [ $i -le 100 ]do let sum=sum+$i let i+=2doneecho $sum
2.利用while循环打印**
示例代码:利用while循环打印一个5x5的*
#!/bin/bashi=1j=1while [ $i -le 5 ]do while [ $j -le 5 ] do echo -n "* " let j++ done echo let i++ let j=1done
3.使用read结合while循环读取文本文件:
示例代码1:
#!/bin/bashfile=$1 #将位置参数1的文件名复制给fileif [ $# -lt 1 ];then #判断用户是否输入了位置参数 echo "Usage:$0 filepath" exitfiwhile read -r line #从file文件中读取文件内容赋值给line(使用参数r会屏蔽文本中的特殊符号,只做输出不做转译)do echo $line #输出文件内容done < $file
示例2:按列读取文件内容
#!/bin/bashfile=$1if [[ $# -lt 1 ]]then echo "Usage: $0 please enter you filepath" exitfiwhile read -r f1 f2 f3 #将文件内容分为三列do echo "file 1:$f1 ===> file 2:$f2 ===> file 3:$f3" #按列输出文件内容done < "$file"
4.while循环中的死循环:
示例:利用死循环,让用户做选择,根据客户的选择打印相应结果
#!/bin/bash#打印菜单while :do echo "********************" echo " menu " echo "1.tima and date" echo "2.system info" echo "3.uesrs are doing" echo "4.exit" echo "********************" read -p "enter you choice [1-4]:" choice#根据客户的选择做相应的操作 case $choice in 1) echo "today is `date +%Y-%m-%d`" echo "time is `date +%H:%M:%S`" read -p "press [enter] key to continue..." Key #暂停循环,提示客户按enter键继续 ;; 2) uname -r read -p "press [enter] key to continue..." Key ;; 3) w read -p "press [enter] key to continue..." Key ;; 4) echo "Bye!" exit 0 ;; *) echo "error" read -p "press [enter] key to continue..." Key ;; esacdone
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对AIDI的支持。如果你想了解更多相关内容请查看下面相关链接
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号