大家好,又见面了,我是你们的朋友全栈君。
1.利用while循环计算1到100的和:
示例代码1:
#!/bin/bashi=1sum=0while [ i -le 100 ]do let sum=sum i let i done
echo $sum
示例代码2:利用while循环计算1到100之间所有奇数之和
#!/bin/bashi=1sum=0while [ i -le 100 ]do let sum=sum i let i =2done
echo $sum
示例代码3:利用while循环计算1到100之间所有偶数之和
#!/bin/bashi=2sum=0while [ i -le 100 ]do let sum=sum i let i =2done
echo $sum
2.利用while循环打印**
示例代码:利用while循环打印一个5×5的*
#!/bin/bashi=1j=1while [ i -le 5 ]do while [ j -le 5 ] do echo -n “* “ let j done echo let i let j=1
done
3.使用read结合while循环读取文本文件:
示例代码1:
#!/bin/bashfile=1 #将位置参数1的文件名复制给fileif [ # -lt 1 ];then #判断用户是否输入了位置参数 echo “Usage:
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:
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 ;; esac
done
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/163972.html原文链接:https://javaforall.cn