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