bash腳本循環語句用法練習
1、使用循環語句寫一個腳本,實現打印出來國際象棋的棋盤
#方法1:使用until循環語句實現 [root@liang7 bin]# cat chess-until.sh #!/bin/bash #Author:liang #Version:1.0 #Description:Print the chess board #Define the number of rows r=1 until [ $r -gt 8 ] ; do #Define the number of columns c=1 until [ $c -gt 8 ] ; do if [ `echo $[(r+c)%2]` -eq 0 ] ;then echo -ne "\033[43m \033[0m" else echo -ne "\033[41m \033[0m" fi let c++ done echo let r++ done #方法2;使用while循環語句實現 [root@liang7 bin]# cat chess-while.sh #!/bin/bash #Author:liang #Version:1.0 #Description:Print the chess board #Define the number of rows r=1 while [ $r -le 8 ] ; do #Define the number of columns c=1 while [ $c -le 8 ] ; do if [ `echo $[(r+c)%2]` -eq 0 ] ;then echo -ne "\033[43m \033[0m" else echo -ne "\033[41m \033[0m" fi let c++ done echo let r++ done #方法3:使用for循環語句實現 [root@liang7 bin]# cat chess-for.sh #!/bin/bash #Author:liang #Version:1.0 #Description:Print the chess board #Define the number of rows for r in {1..8} ; do #Define the number of columns for c in {1..8} ; do if [ `echo $[(r+c)%2]` -eq 0 ] ;then echo -ne "\033[43m \033[0m" else echo -ne "\033[41m \033[0m" fi done echo done
2、使用循環語句寫一個腳本,實現用“*”打印出等腰三角形的形狀
#方法1: [root@liang7 bin]# cat sjx1.sh #!/bin/bash #Author:liang #Version:1.0 #Description:Print out an isosceles triangle read -p "請輸入想要的三角形層數:" num until echo $num|grep -q '^[0-9]\+$' ; do read -p "請重新輸入三角形層數:" num done if [ $num -eq 0 -o $num -eq 1 ] ; then echo "您輸入的層數無法組成三角形,輸入的層數應大于等于2" else for line in `seq 1 $num`; do let n=$num-$line m=1 while [ $n -gt 0 ] ; do echo -n " " let n-- done while [ `echo $[line*2-1]` -ge $m ]; do echo -n "*" let m++ done echo done fi 方法2: [root@liang7 bin]# cat sjx2.sh #!/bin/bash #Author:liang #Version:1.0 #Description:Print out an isosceles triangle read -p "請輸入想要的三角形層數:" num until echo $num|grep -q '^[0-9]\+$' ; do read -p "請重新輸入三角形層數:" num done if [ $num -eq 0 -o $num -eq 1 ] ; then echo "您輸入的層數無法組成三角形,輸入的層數應大于等于2" else for line in `seq 1 $num` ; do for((n=(num-line);n>0;n--)); do echo -n " " done for((m=1;(line*2-1)>=m;m++)); do echo -n "*" done echo done fi
原創文章,作者:苦澀咖啡,如若轉載,請注明出處:http://www.www58058.com/37114