Shell脚本——for,while,until循环
程序员文章站
2023-04-04 19:04:10
1、for循环: 语句格式: for i in 循环判断 do 循环体 done 举例:九九乘法表(for循环版本) 2、while循环 语句格式: while 循环判断 do 循环体 done 举例:猜拳游戏 3、until循环 until循环与while循环类似 语句格式: until 循环判断 ......
1、for循环:
语句格式:
for i in 循环判断
do
循环体
done
举例:九九乘法表(for循环版本)
#!/bin/bash
# author: sean martin
# blog: https://www.cnblogs.com/shy13138/
# time: 2019-08-16 10:35:48
# name: 99for.sh
# version: v1.0
for i in {1..9};do
for j in $(seq $i);do
echo -ne "$i*$j=$((i*j)) "
done
echo ''
done
2、while循环
语句格式:
while 循环判断
do
循环体
done
举例:猜拳游戏
#!/bin/bash
# author: sean martin
# blog: https://www.cnblogs.com/shy13138/
# time: 2019-08-16 10:35:48
# name: caiquan.sh
# version: v1.0
j=1
while [ $j -le 5 ]
do
echo "1.石头 2.剪刀 3.布 "
read -p "请出拳1-3:" i
if [ $i -ne 1 -o $i -ne 2 -o $i -ne 3 ];then
echo "请输入1-3之间的数"
fi
game=(石头 剪刀 布)
num=$((random%3))
echo computer=${game[$num]}
case $i in
1)
if [ 0 -eq $num ];then
echo "平局"
elif [ 1 -eq $num ];then
echo "你输了"
else
echo "你赢了"
fi;;
2)
if [ 1 -eq $num ];then
echo "平局"
elif [ 0 -eq $num ];then
echo "你输了"
else
echo "你赢了"
fi;;
3)
if [ 2 -eq $num ];then
echo "平局"
elif [ 1 -eq $num ];then
echo "你输了"
else
echo "你赢了"
fi;;
esac
let j++
done
3、until循环
until循环与while循环类似
语句格式:
until 循环判断
do
循环体
done
举例:
99乘法表(until版)
#!/bin/bash
# author: sean martin
# blog: https://www.cnblogs.com/shy13138/
# time: 2019-08-16 10:35:48
# name: 99until.sh
# version: v1.0
i=1
until [[ $i -gt 9 ]]
do
j=1
until [[ $j -gt $i ]]
do
let "sum = $i*$j"
echo -n -e "$i*$j=$sum\t"
let "j++"
done
echo ""
let "i++"
done