Shell脚本——for,while,until循环

Posted shy13138

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

  

以上是关于Shell脚本——for,while,until循环的主要内容,如果未能解决你的问题,请参考以下文章

shell脚本编程循环之for/while/untill循环

Shell脚本之while循环

Shell脚本------循环语句(for,while,until循环语句)

Shell编程Shell中for循环while循环until循环语句

Shell编程Shell中for循环while循环until循环语句

if for while until case select 命令