Shell脚本——for,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

  

猜你喜欢

转载自www.cnblogs.com/shy13138/p/11365611.html